【发布时间】:2016-10-05 16:02:35
【问题描述】:
我正在构建一个 web 应用程序,在服务器端使用 node js,在客户端使用 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。回复 预检请求未通过访问控制检查:通配符 '*' 不能在 'Access-Control-Allow-Origin' 标头中使用 凭据标志为真。原点“http://localhost:4000”是 因此不允许访问。
我对 ionic 应用也有同样的问题。
这背后的原因可能是什么?
我正在从多个域以及移动和网络等不同应用程序访问这些 API。
【问题讨论】:
-
飞行前请求使用
'options'动词而不是'get',因此您需要一个处理程序。您提出的特定请求(可能是自定义标头)有一些东西会强制使用'options'预检。 -
尝试使用
Access-Control-Allow-Origin标头成为特定域。 -
请参阅 How to enable CORS in Express 以获得
OPTIONS支持。 -
@jfriend00 我查看了您的第一条评论,但我没有设置任何自定义标题。
-
@nitinmegamind 看来你可能正面临这个问题:stackoverflow.com/questions/10883211/…
标签: javascript angularjs node.js ionic-framework cors