我正在尝试使用 Angular 1、Nodejs 和 Express 创建单页应用程序。我正在使用 Angular 的 $http 发布功能发布请求,我将请求中的 header 值传递给 API 端点。
我在 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
图书馆。
在我的 app.js 中,我添加了以下几行:
var cors = require('cors');
var app = express();
app.use(cors());
这是我的完整 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 页面
<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>
但是还是不行。
任何人都可以告诉我如何以及在哪里更新我的代码以解决“Access-Control-Allow-Origin”通配符问题吗?
最佳答案
虽然@muratgozel 的回答部分正确,但让我更深入地了解一下 CORS 以及导致问题的原因。当您的浏览器发送跨源响应时,它会在 header 中给出它的来源。服务器响应还提供了一个名为 Access-Control-Allow-Origin 的 header 。当您在 express 应用程序中使用实例化 'cors' 模块时,Access-Control-Allow-Origin header 设置为 '*' 通配符,这基本上意味着它(express 应用程序的)服务器资源是公共(public)的并且可以可以从任何地方的任何代码访问,但是此通配符的限制是请求中不允许使用某些请求 header ,例如 Authorization。您对 index.html 页面的请求有一组 headers 。您应该查看 header ,或者您可以简单地执行@muratgozel 所说的并实例化具有特定来源的 cors 除了将凭据选项设置为 true
app.use(cors({ origin: 'http://example.com' , credentials : true}));
关于javascript - 'Access-Control-Allow-Origin' 的 Nodejs Express CORS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44145619/