0

I'm trying to fetch data from the backend, but I get a weird error. If anyone has a clue how to fix please help.

My code

  async componentDidMount() {
    const url = 'http://localhost:8080/zoom';
    const response = await fetch(url);
    const data = await response.json();
    console.log(data)
  }

Error:

Access to fetch at 'http://localhost:8080/zoom' from origin 'http://localhost:3000' has been blocked by CORS policy: 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.
angels7
  • 143
  • 2
  • 8
  • Maybe you'll find your answer [here](https://stackoverflow.com/questions/43262121/trying-to-use-fetch-and-pass-in-mode-no-cors?rq=1). Either way this question has been asked before a few times. Basically the browser blocks cross-origin responses unless you specify the CORS headers in the response. – OPearl Apr 30 '20 at 12:04

2 Answers2

0

It is not a 'weird' error. It's a security measurement.

See this to understand what is CORS

Since you are using Port 3000, I assume that you are using NodeJS (with Express) for backend server.

You can install cors package from NPM and use it to allow your front-end domain (in this case it is localhost:8080) for Cross Origin Resource Sharing.

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

const corsOptions = {
    origin: 'http://localhost:8080',
    optionsSuccessStatus: 200
  }

app.use(cors(corsOptions));
Alper Güven
  • 329
  • 4
  • 15
0

This is because of your origin domain is not whitelisted. Instead of adding an additional cors package and also cors sometimes may not work, so you can whitelist your selected domains, which means that you are giving entire access to your backend.

app.use(function (req, res, next) {
var allowedOrigins = ["http://localhost:3000"];
var origin = req.headers.origin;
if(allowedOrigins.indexOf(origin) > -1){
   res.setHeader('Access-Control-Allow-Origin', origin);
}
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
Arun Kumar
  • 355
  • 3
  • 10