Angular / Node CORS问题

我正在服务器端build立一个节点js的Web应用程序,并在客户端build立angular度。

我正在运行不同的域上的服务器和其他域上的客户端。

我的服务器端代码:

var express = require('express'); var app = express(); var http = require("http").createServer(app); var request = require('request'); app.use(function(req, res, next) { console.log(req.headers); res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization"); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); next(); }); app.get('/api/hello', function(req, res){ var data = {'message': 'Server is running'} res.jsonp(data); }); http.listen(5000); 

和在客户端(Angular)。

 angular.controller('myController', function($state, $http){ $http.get('http://localhost:5000/api/hello').success(function(response, status) { console.log(responce); }).error( function(error, status) { console.log(error) }); }); 

我的服务器在端口5000上运行,而我的客户端在端口4000上运行在不同的域上。

当我从客户端发送上述请求时,在浏览器控制台中出现以下错误,

XMLHttpRequest无法加载http:// localhost:5000 / api / hello 。 对预检请求的响应未通过访问控制检查:当凭证标志为true时,通配符“*”不能用于“Access-Control-Allow-Origin”标头中。 原因' http:// localhost:4000 '因此不被允许访问。

我也有与离子应用程序相同的问题。

这背后的原因是什么?

我正在从多个域和从不同的应用程序,如移动和networking访问这些API。

你可以像下面给出的那样使用cors

安装Cors模块

npm install --save cors

服务器代码

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

angular

 angular.controller('myController', function($state, $http){ $http .get('http://localhost:5000/api/hello') .then(function(response) { console.log(responce); }, function(error, status) { console.log(error) }); }); 

在路线我做了一个文件命名为corsheaders.js其中包含

 module.exports = function (req, res, next) { if (allowedHosts.indexOf(req.headers.origin) > -1) { res.header('Access-Control-Allow-Origin', req.headers.origin); res.header('Access-Control-Allow-Credentials', true); res.header('Access-Control-Allow-Methods', 'GET,POST,DELETE,OPTIONS,PUT'); res.header('Access-Control-Allow-Headers', 'Content-Type'); } next(); }; 

这里allowedHosts是一个数组,其中包含我所允许的域名,在app.js中我使用这个文件

 app.use(require('./routes/corsheaders')); 

在那个错误,看起来好像你的Access-Control-Allow-Credentials头可能会返回为真? 你的回应包含哪些标题?

尝试添加res.header('Access-Control-Allow-Credentials', false); 当你添加你的标题,看看是否解决了这个特定的错误。

另外,是否有一个你为什么包含http.createServer(app)代码的原因? ExpressJS应用程序通常通过直接调用app.listen来启动,就像这样可能是问题所在。

 app.listen(5000, function () { console.log('Example app listening on port 5000!'); });