在 Node.js/Express 和 AngularJS 中发出 CORS 请求
Posted
技术标签:
【中文标题】在 Node.js/Express 和 AngularJS 中发出 CORS 请求【英文标题】:Making CORS Request in Node.js/Express and AngularJS 【发布时间】:2015-08-15 09:52:53 【问题描述】:我在堆栈溢出中看到了很多答案,说设置响应标头会使您发出“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 的新手
【问题讨论】:
在你的服务器上设置cors不会在其他服务器上启用cors,目标服务器必须启用它 您是否尝试从 localhost:3000 访问 domainA.com ?如果是这样,您是 domainA.com 的所有者吗?从我所看到的,您必须在 domainA.com 服务器的请求中添加标头。几个小时前我已经回答了同样的问题:***.com/questions/30577886/… 我不是 domainA.com 的所有者。那么,我如何从该 URL 访问内容我是否需要通过 example.xxxxx.com 而不是本地主机运行我的应用程序? @cl3m 【参考方案1】:当您使用 CORS 传递凭据时,您需要锁定接受的来源。尝试将您的来源从 * 更改为“localhost:3000”
见cross origin resource sharing with credentials
【讨论】:
【参考方案2】:更改标题信息
res.setHeader("Access-Control-Allow-Origin", "*");
到
res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
【讨论】:
我认为这种变化必须发生在 domainA.com 中。但我不是它的所有者。所以,我是否需要通过 example.xxxxxx.com 而不是本地主机运行我的应用程序。 那无济于事,如果您不是网站的所有者,那么这将违反 CORS 签名。该网站必须允许您使用其数据。 我可以从以下域运行我的应用程序:example.xxxxx.com.Should 我需要这样做吗?如果我看到控制台错误消息它说“'Access-Control-Allow-Origin'标头的值'example.xxxxx.com''。所以我mi8能够从url访问内容。如果是,请纠正我没有错?? 是的,如果你可以访问'example.xxxxx.com',那么你就可以访问数据了。【参考方案3】:如果您不是 domainA 的所有者,则无法从该域发送 CORS 标头。您可以将 Node 服务器用作中间件,并将来自服务器的请求代理到 domainA。您的服务器可以将 CORS 标头发送回您的 Angular 应用程序。带有hapi
和needle
的伪代码:
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 ' )
)
【讨论】:
以上是关于在 Node.js/Express 和 AngularJS 中发出 CORS 请求的主要内容,如果未能解决你的问题,请参考以下文章
在单个 Node.js + Express 响应中发送图像和 JSON 数据
脊椎、node.js (express) 和 Access-Control-Allow-Origin
使用 Node.JS、Express 和 EJS 实现 browserify 的示例