脊柱,node.js中(EX preSS)和访问控制 - 允许 - 原产地 [英] spine, node.js (express) and Access-Control-Allow-Origin

查看:162
本文介绍了脊柱,node.js中(EX preSS)和访问控制 - 允许 - 原产地的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发展我的本地PC的应用程序。前端应与spinejs和后端API和node.js中建 脊柱是在端口9294上运行,并Node.js的是在端口3000上运行。 在脊柱我已经添加到我的模型如下:

I'm developing an app on my local pc. THe frontend should be built with spinejs and the backend-api with node.js. Spine is running on port 9294 and node.js is running on port 3000. in Spine I've added to my model the following:

@url: "http:localhost:3000/posts"

在我的前preSS服务器

and in my express server

app.get('/posts', function(req, res){
  console.log("giving ALL the posts");
  res.header("Access-Control-Allow-Origin", "*")
  res.json(posts);
});

不过,我总是得到镀铬以下埃罗:

But I'm always getting the following erro in chrome:

XMLHttpRequest cannot load http://localhost:3000/posts. Origin http://localhost:9294 is not allowed by Access-Control-Allow-Origin.

我必须做什么,我可以正常访问我的API?我虽然增加的响应中的头并解决问题。

What must I do that I can access my api properly? I though adding the header in the responses does fix the problem.

推荐答案

app.get 将只对 GET 请求。如果浏览器是$ P $与选项pflighting它的要求,前preSS将抛出一个错误,因为它没有任何监听这些请求。尝试除了你加入这个code,看看它的工作原理:

app.get will only respond to GET requests. If the browser is preflighting it with an OPTIONS request, express will throw an error because it doesn't have any listeners for those requests. Try adding this code in addition to yours and see if it works:

app.options('/posts', function(req, res){
  console.log("writing headers only");
  res.header("Access-Control-Allow-Origin", "*");
  res.end('');
});

另外请注意:如果你发送的cookie的请求( withcredentials = TRUE ),那么访问控制 - 允许 - 原产地头不能 * ,它必须是在原产地头的精确值,浏览器自动添加到像这样的Ajax请求:

Also note: if you're sending cookies with the request (withcredentials=true), then the Access-Control-Allow-Origin header cannot be *, it must be the exact value in the Origin header that the browser automatically adds to the ajax request like so:

res.header("Access-Control-Allow-Origin", req.headers.origin);

这是出于安全原因 - 如果你正在做的东西,需要的cookie,那么它更可能是你将要实际检查原产地是允许的网站为了避免 CSRF攻击

This is for security reasons - if you're doing something that requires cookies, then it is more likely that you will want to actually check that the origin is an allowed website in order to avoid CSRF attacks.

这篇关于脊柱,node.js中(EX preSS)和访问控制 - 允许 - 原产地的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆