简体   繁体   中英

Unable to solve this in NODE.JS, No 'Access-Control-Allow-Origin' header is present on the requested resource in (nodejs + angularjs)

I am new to node.js and trying to make Rest API, now my REST API working fine but whenever i called this services through angularjs, it gives me "access-control-allow-origin" error. However, i added this code on server side :-

var express = require("express");  
var app = express();
var router = express.Router();

app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    res.header('Access-Control-Allow-Credentials', true);
    return next();
});

But its not working for me, i searched a lot but didn't get feasible solution, please help me out.

Error is :- 在此处输入图片说明

You are using http module of angular, if yes, then Angular sends a pre-flight options before actual request. Your server should return 20X for OPTIONS for angular to make actual request.

You can avoid this by handling OPTIONS separately ,

app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    res.header('Access-Control-Allow-Credentials', true);


  if (req.method == "OPTIONS") {
          response.statusCode = 200 //although correct code should be 204,
      return;
        }

    return next();
});

Also a more exhaustive and less restrictive CORS filter will look like below, use it as per your need

            resp.header("Access-Control-Allow-Origin", "*");
            resp.header("Access-Control-Allow-Credentials", "true");
            resp.header("Access-Control-Allow-Methods", "POST, GET, PUT,PATCH, OPTIONS, DELETE");
            resp.header("Access-Control-Max-Age", "3600");
            resp.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization, Origin, Accept, Access-Control-Request-Method, Access-Control-Request-Headers");

            resp.header("Access-Control-Expose-Headers", "Authorization");

The browser sends a preflight request before making the actual request. You need to add code for handling this requests, Try this in your server side code.

const cors = require('cors')
const corsOptions = {
  origin: '*'
}
app.use(cors(corsOptions))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM