RhinoBomb
RhinoBomb

Reputation: 463

Enabled CORS in node/express but getting "Response to preflight request doesn't pass access control check"

I am getting the error :

Failed to load http://localhost:3000/users/register: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

On the front end i'm using axios:

const instance = axios.create({
  baseURL: 'http://localhost:3000',
  timeout: 1000,
  headers: {"Access-Control-Allow-Origin": "*"}
});

instance.post('/users/register').then((res) => {
  console.log(res);
}).catch((err) => {
  console.log(err);
});

and on the server-side using express i am using cors:

var cors = require('cors');
var corsOptions = {
   origin: '*',
   optionsSuccessStatus: 200 
}
app.use(cors(corsOptions));

I am getting a response code of 200 and I do see the 'Access-Control-Allow-Origin' header but i'm not getting anything on the server-side. Any ideas?

Upvotes: 1

Views: 5011

Answers (1)

Nicholas Yang
Nicholas Yang

Reputation: 317

You most likely need to also explicitly enable support for OPTIONS requests (i.e. "CORS preflight"). See https://github.com/expressjs/cors#enabling-cors-pre-flight for details on how to do that.

For your specific case, I would add the following:

app.options('/users/register', cors(corsOptions));

Or if you want to enable it for all requests:

app.options('*', cors(corsOptions));

Upvotes: 4

Related Questions