在Node.js / Express和AngularJS中进行CORS请求

时间:2015-06-01 19:45:58

标签: javascript angularjs node.js express cors

我在堆栈溢出中看到很多答案,说设置响应头会让你“CORS”请求。但没有解决方案对我有用。我写了以下代码:

//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的新手

3 个答案:

答案 0 :(得分:0)

当您使用CORS传递凭据时,您需要锁定已接受的来源。尝试将您的起源从*更改为“localhost:3000”

请参阅cross origin resource sharing with credentials

答案 1 :(得分:0)

更改标题信息

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

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

答案 2 :(得分:0)

如果您不是domainA的所有者,则无法从该域发送CORS标头。您可以将节点服务器用作中间件,并将请求从服务器代理到domainA。您的服务器可以将CORS标头发送回您的角度应用程序。伪代码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 }' )
})