Nodejs Express CORS问题,“访问控制允许来源" [英] Nodejs Express CORS issue with 'Access-Control-Allow-Origin'

查看:92
本文介绍了Nodejs Express CORS问题,“访问控制允许来源"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Angular 1,Nodejs和Express创建一个单页应用程序.我正在使用Angular的$ http发布功能发布请求,将请求中的标头值传递给API端点.

I'm trying to create a single page app using Angular 1, Nodejs and Express. I'm using Angular's $http post feature to post a request where I pass header values in the request to an API endpoint.

我在Chrome中遇到一条错误消息:

I am encountering an error message in Chrome:

XMLHttpRequest cannot load 
http://localhost:7878/EIAMIDSupportREST/EIAMIDSupport/updateEIAMID. The 
value of the 'Access-Control-Allow-Origin' header in the response must not 
be the wildcard '*' when the request's credentials mode is 'include'. Origin 
'http://localhost:3000' is therefore not allowed access. The credentials 
mode of requests initiated by the XMLHttpRequest is controlled by the 
withCredentials attribute.

使用此请求正文:

HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,PUT,POST,PATCH,DELETE
Access-Control-Allow-Headers: Content-Type
Allow: POST
Content-Type: text/html; charset=utf-8
Content-Length: 4
Date: Tue, 23 May 2017 23:32:15 GMT
Connection: keep-alive

要解决CORS问题,我已经npm安装了 cors 库.

To remedy the CORS issue, I've npm installed the cors library.

在我的app.js中,添加以下几行:

In my app.js, I have the add the following lines:

var cors = require('cors');
var app = express();
app.use(cors());

这是我完整的app.js:

Here is my full app.js:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var cons = require('consolidate');
//enable CORS 
var cors = require('cors');
var app = express();
app.use(cors({ origin: 'http://localhost:3000' , credentials :  true,  methods: 'GET,PUT,POST,OPTIONS', allowedHeaders: 'Content-Type,Authorization' }));
// view engine setup
app.engine('html', cons.swig)
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

这是我的index.html页面

And here is my index.html page

<html>
<head>
<script 

src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("app", []);
   app.controller("HttpGetController", function ($scope, $http) {
       $scope.SendData = function () {
         var req = {
          method: 'POST',
          url: 'http://localhost:7878/EIAMIDSupportREST/EIAMIDSupport/updateEIAMID',
          withCredentials: true,
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Basic user:password'
          }
         }
         $http(req)
           .then(function(data, status, header, config)
             {
               $scope.PostDataResponse = data,
               console.log($scope.PostDataResponse);
             })
             .catch(function(data, status, header, config)
             {
                $scope.PostDataResponse = data,
                console.log($scope.PostDataResponse);
             });

       };

     });
</script>
</head>
<body>
  <div ng-app="app">
    <div ng-controller="HttpGetController">
      <button  ng-click="SendData()" >Link Accounts</button>
      <hr />AND THE RESPONSE IS:{{ PostDataResponse }}
    </div>
  </div>
</body>
</html>

但是,它仍然不起作用.

However, it still does not work.

任何人都可以建议我更新代码的方式和位置,以解决"Access-Control-Allow-Origin"通配符问题吗?

Can anyone please advise how and where I need to update my code to fix the 'Access-Control-Allow-Origin' wildcard issue?

推荐答案

虽然@muratgozel的回答部分正确,但让我更深入地介绍CORS及其原因.当您的浏览器发送跨域响应时,它在标头中给出它的原点.服务器响应还提供了一个名为Access-Control-Allow-Origin的标头.当您在快速应用程序中使用实例化"cors"模块时,Access-Control-Allow-Origin标头设置为"*"通配符,这基本上意味着该服务器资源(快速应用程序)是公共的,并且可以可以从任何地方的任何代码访问,但是此通配符的限制是请求中不允许使用某些请求标头,例如Authorization.您在index.html页面上的请求具有的标头集.您应该查看标题,也可以简单地执行@muratgozel所说的操作并实例化具有特定来源的cors,只是将凭据选项设置为

While the answer by @muratgozel is partially correct , let me go a little deeper on CORS and why the issue is caused . When your browser sends a cross-origin response , it gives it's Origin in the header . The server response also gives a header called Access-Control-Allow-Origin. When you use instantiate the 'cors' module in your express app , the Access-Control-Allow-Origin header is set to be '*' a wildcard , which basically means it this server resource (of the express app) is public and can be accessed from any code anywhere, However the limitation of this wildcard is that certain request headers such as Authorization are not allowed in the request. Your request from the index.html page has it's set of headers . Either you should look into the headers or you can simply do what @muratgozel said and instantiate cors with a specific origin Except just set the credentials option to true

app.use(cors({ origin: 'http://example.com' , credentials :  true}));

这篇关于Nodejs Express CORS问题,“访问控制允许来源"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆