Home > Back-end >  CORS error with Angular UI and Node backend
CORS error with Angular UI and Node backend

Time:12-26

I'm new to node and need some help.

I'm getting: Access to XMLHttpRequest at 'http://localhost:3000/api/auth/signin' from origin 'http://localhost:4200' has been blocked by CORS policy:

my angular app is launching from http://localhost:4200

And I'm making an api request (which works on postman) to http://localhost:3000/api/auth/signin

but I'm getting CORS errors.

In my node server.js, I have the following configured:

    app.use(function (req, res, next) {
      res.setHeader("Access-Control-Allow-Origin", "*");
      res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      res.setHeader('Access-Control-Allow-Methods', "GET, POST, PATCH, DELETE, OPTIONS");
      next();
    });

And I can post data using postman to: localhost:3000/api/auth/signin

CodePudding user response:

It's because Browser will send something called preflight request, and Postman will not. So, your server has to respond to these preflight requests first, in order for Browser to proceed with original request.

Your code will just call next() which will proceed to the next middleware, but what will that middleware do after? You should send 200 on OPTIONS request immediately.


Alternatively, you can quickly add cors logic with cors package:

const cors = require('cors');

...

app.use(cors());

CodePudding user response:

CORS stands for Cross-origin resource sharing. That allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.

To enable cors in Node js, type npm i cors OR yarn add cors

USAGE:-

Common Js

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

cors ({origin: '*'}) // Enable CORS for all routes and allow any domain to make requests


ES6 Modules

import cors from 'cors'
const app = express()

cors ({origin: '*'}) // Enable CORS for all routes and allow any domain to make requests

The cors middleware allows you to specify the allowed origins, methods, and headers, and it will automatically add the necessary Access-Control-Allow-* headers to the response.

cors doc

  • Related