-1

In Express server running on port 8080 I have;

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost:8081");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

Request from port 8081

fetch('http://localhost:8080/...')
      .then((response) => response.json())
      .then((json) => {
        let jsonStr = JSON.stringify(json);
        console.log(jsonStr)
      })
      .catch((error) => console.log(error))

Error I get:

Access to fetch at 'http://localhost:8080/...' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

If I simply manually enter express url on browser I see the JSON I'm trying to fetch.

I have read multiple post to resolve this issue but I still can't seem to be able to resolve it.

How should I fetch to avoid this error?

user2300867
  • 593
  • 1
  • 12
  • 28

2 Answers2

0

You're fetching from a different port (8081) and that's why you're getting the CORS error message. Change the Access Control policy as follows:

  res.header("Access-Control-Allow-Origin", "http://localhost:*");

This link can come in handy.

Kostas Minaidis
  • 4,681
  • 3
  • 17
  • 25
0

You can use cors to get rid of this;

const express = require('express')
const cors = require('cors')
const app = express()

app.use(cors())
Ved
  • 11,837
  • 5
  • 42
  • 60