-2

I have a react.js front end react app calling a node.js backend api. They are running on different ports. I have the following set in the backend response header.

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader(
    'Access-Control-Allow-Methods',
    'OPTIONS, GET, POST, PUT, PATCH, DELETE'
  );
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  next();
});

I am still seeing the following CORS error when it calls the backend.

Access to fetch at 'http://localhost:8080/feed/post' 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.

Making Post and Get requests with no custom header values.

Andy N
  • 1,013
  • 9
  • 25
  • 1
    Your custom CORS middleware doesn't handle [pre-flight requests](https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request). Please just use the industry standard [cors middleware](https://github.com/expressjs/cors) – Phil Oct 06 '22 at 01:11

1 Answers1

-1

use this CORS middleware

$ npm install cors

in your app.js add this

const cors = require("cors");
//add in your middlewares
app.use(cors());
Stacks Queue
  • 848
  • 7
  • 18
  • Also added app.options('*', cors()) to my app.js. Still getting the error – Andy N Oct 06 '22 at 01:45
  • app.use(cors({ credentials: true, origin: true })); Node.js should give the option of 'cors' as follows, and the option of 'header' should also be given in reaction. – 한대현 Oct 06 '22 at 01:59
  • Looks like this needs to be set before the other app.use() ones. Otherwise will not work. – Andy N Oct 06 '22 at 02:46