0

I have created a React Application with Node Express Back End.But when I run the app data is not displaying and I am getting an error "Access to fetch at 'https://75f37vbl70.execute-api.us-east-1.amazonaws.com/InstanceDetails/qualys-agent-check/' 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"

This is my App.jsx file.

const routes=require('./components/Routes.js')
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({ origin: true }));
const port = process.env.PORT || 5000;

/* apps.use(
  cors({
    origin: ['*'],
    methods: ["*"],
    credentials: true // enable set cookie
  })
);

 */
/* app.options('*',cors())
// console.log that your server is up and running */
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*"); 
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

// create a GET route
/* app.get('/', (req, res) => {
  res.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' });
}); */
app.use('/',routes)
app.listen(port, () => console.log(`Listening on port ${port}`));
  • 1
    Does this answer your question? [How does Access-Control-Allow-Origin header work?](https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work) – zero298 Sep 08 '20 at 13:39

1 Answers1

2

This is not related to React. Basically you need to enable CORS in your backend code. Which means you are enabling any other server which does not have the origin same as where you have deployed your Node application to fetch the data using HTTP. Here is how you can do it if you are using Express -

Install the cors middleware.

npm i cors --save 

Use it in your index.js file before specifying your routes -

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

app.use(cors({ origin: true }));
rex
  • 359
  • 1
  • 5