angular度$ http请求从80端口到另一个端口

我试图从一个angular度1项目使用$ http方法来打击本地服务器上的端口3000的节点API,但我得到这个错误:

XMLHttpRequest无法加载http:// localhost:3000 / login 。 请求标头字段预检响应中的Access-Control-Allow-Headers不允许授权。

我还在节点js中添加了Access-Control-Allow-Origin : *

 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 (eg in case you use sessions) // res.setHeader('Access-Control-Allow-Credentials', false); next(); }); 

而我的angular码是:

 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); }); 

但是我仍然得到这个错误。

错误在指定的预检响应中。 所以你需要处理OPTIONS方法:

 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 (eg in case you use sessions) // res.setHeader('Access-Control-Allow-Credentials', false); if (req.method === "OPTIONS") { return res.status(200).end(); } return next(); }); 

这是由于浏览器处理跨域请求的方式。 OPTIONS请求(预检)在您的POST之前发送,以获得允许的来源,标题和方法。