在Node.js / Express和AngularJS中创buildCORS请求

我已经看到很多堆栈溢出的答案,说设置响应头会让你“CORS”request.But没有解决scheme为我工作。我写了下面的代码:

//Server.js Code var express = require('express'), app = express(); app.all('*',function(req, res, next) { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.setHeader('Access-Control-Allow-Credentials', true); res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS'); next(); 

我试图从客户端使用$ http访问URL中的内容:

 //Controller.js $http.get('http://domainA.com/a/ipadapi.php?id=135&client=ipad').success(function(response){ alert("I got response"); }); 

它在控制台中显示以下错误。

 XMLHttpRequest cannot load http://domainA.com/a/ipadapi.php?id=135&client=ipad The 'Access-Control-Allow-Origin' header has a value 'http://example.xxxxx.com' that is not equal to the supplied origin. Origin 'http://localhost:3000' is therefore not allowed access. 

注意:我是nodeJS,Express和AngularJs的新手

当您使用CORS传递证书时,您需要locking接受的来源。 尝试将您的起源从*更改为“localhost:3000”

查看与凭证共享的跨源资源共享

更改标题信息

res.setHeader("Access-Control-Allow-Origin", "*");

res.header('Access-Control-Allow-Origin', 'http://localhost:3000');

如果您不是domainA的所有者,那么您不能从该域发送CORS头。 您可以使用您的节点服务器作为中间件,并将您的服务器的请求代理到domainA。 你的服务器可以发送CORS头回你的angular度的应用程序。 与hapineedle伪代码:

 import Hapi from 'hapi' import needle from 'needle' const server = new Hapi.Server() server.connection({ port: 9090 , routes: { cors: true } }) const handler = (req, reply) => { const url = 'https://domainA.com' , data = { body: 'code' } needle.post(url, 'body=${data.body}', function(err, res) { let json = JSON.parse(res.body) reply(json.data) }) } server.route({ method: 'GET', path: '/route/{id}', handler: handler } ) server.start( err => { if( err ) { console.error( 'Error was handled!' ) console.error( err ) } console.log( 'Server started at ${ server.info.uri }' ) })