Angularjs 从80端口到另一端口的角度$http请求
我试图使用$http方法从angular 1项目中点击本地服务器上端口为3000的节点api,但出现以下错误: 无法加载XMLHttpRequest。请求头 中的访问控制允许标头不允许字段授权 飞行前反应 我还在节点js中添加了Angularjs 从80端口到另一端口的角度$http请求,angularjs,node.js,http,cors,cross-domain,Angularjs,Node.js,Http,Cors,Cross Domain,我试图使用$http方法从angular 1项目中点击本地服务器上端口为3000的节点api,但出现以下错误: 无法加载XMLHttpRequest。请求头 中的访问控制允许标头不允许字段授权 飞行前反应 我还在节点js中添加了访问控制允许原点:,如下所示: req.on('end', function() { req.rawBody = req.rawBody.toString('utf8'); res.setHeader('Access-Control-Allow-Origi
访问控制允许原点:
,如下所示:
req.on('end', function() {
req.rawBody = req.rawBody.toString('utf8');
res.setHeader('Access-Control-Allow-Origin', 'http://localhost');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', '*');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', '*');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
// res.setHeader('Access-Control-Allow-Credentials', false);
next();
});
我的角度代码是:
var req = {
method: 'POST',
url: 'http://localhost:3000/login',
headers: {
'Content-Type': 'application/json',
// 'cache-control': 'no-cache'
},
data: { username: username, password: password },
json: true
};
$http(req).then(function successCallback(response){
console.log(response);
}, function errorCallback(response){
console.log("Error : ");
console.log(response);
});
但是我仍然得到了这个错误。错误在飞行前响应中,具体如下。 因此,您需要处理选项方法:
req.on('end', function() {
req.rawBody = req.rawBody.toString('utf8');
res.setHeader('Access-Control-Allow-Origin', 'http://localhost');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', '*');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', '*');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
// res.setHeader('Access-Control-Allow-Credentials', false);
if (req.method === "OPTIONS") {
return res.status(200).end();
}
return next();
});
这是由于浏览器处理跨源请求的方式。选项请求(飞行前)在您的帖子之前发送,以获取允许的来源、标题和方法