Jam*_*som 87 rest heroku node.js cors express
我已经写在快递框架REST API为从Chrome中的JS控制台,地址栏等要求,现在我试图得到它的工作从另一个应用程序请求node.js的工作,在不同的域(CORS).
由javascript前端自动生成的第一个请求是/ api/search?uri =,并且似乎在"预检"OPTIONS请求中失败.
在我的快递应用程序中,我正在添加CORS标头,使用:
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};
Run Code Online (Sandbox Code Playgroud)
和:
app.configure(function () {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(allowCrossDomain);
app.use(express.static(path.join(application_root, "public")));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
Run Code Online (Sandbox Code Playgroud)
在Chrome控制台中,我得到以下标题:
请求网址:http://furious-night-5419.herokuapp.com/api/search?uri = http%3A%2F%2Flocalhost%3A5000%2Fcollections%2F1%2Fdocuments%2F1
请求方法:选项
状态代码:200 OK
请求标题
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:origin, x-annotator-auth-token, accept
Access-Control-Request-Method:GET
Connection:keep-alive
Host:furious-night-5419.herokuapp.com
Origin:http://localhost:5000
Referer:http://localhost:5000/collections/1/documents/1
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5
Run Code Online (Sandbox Code Playgroud)
查询字符串参数
uri:http://localhost:5000/collections/1/documents/1
Run Code Online (Sandbox Code Playgroud)
响应标题
Allow:GET
Connection:keep-alive
Content-Length:3
Content-Type:text/html; charset=utf-8
X-Powered-By:Express
Run Code Online (Sandbox Code Playgroud)
这看起来像API应用程序发送的标头缺少吗?
谢谢.
Ole*_*gas 59
我已经在一个干净的ExpressJS应用程序上解决了你的代码,它工作得很好.
尝试将您app.use(allowCrossDomain)移至配置功能的顶部.
我将其添加为答案只是因为原始帖子是作为评论放入的,因此当我第一次浏览此页面时,它确实被您忽略了。
正如 @ConnorLeech 在他对上面接受的答案的评论中指出的那样,有一个非常方便的 npm 包,毫不奇怪地称为cors。它的使用非常简单(再次,抄袭自 Leech 先生的答案),并且也可以按照其文档var cors = require('cors'); app.use(cors());中概述的更严格、更可配置的方式应用。
还值得指出的是,我上面提到的原始评论是在 2014 年做出的。现在是 2019 年,查看npm 包的 github 页面, repo 的更新时间为 9 天前。
| 归档时间: |
|
| 查看次数: |
65652 次 |
| 最近记录: |