如何允许CORS? [英] How to allow CORS?
问题描述
我试图在使用Express.js Web框架的Node.js应用程序中支持CORS。我已阅读 Google小组讨论,了解如何处理此问题,并阅读关于CORS如何工作的几篇文章。首先,我这样做(代码是用CoffeeScript语法编写的):
I am trying to support CORS in my Node.js application that uses the Express.js web framework. I have read a Google group discussion about how to handle this, and read a few articles about how CORS works. First, I did this (code is written in CoffeeScript syntax):
app.options "*", (req, res) ->
res.header 'Access-Control-Allow-Origin', '*'
res.header 'Access-Control-Allow-Credentials', true
# try: 'POST, GET, PUT, DELETE, OPTIONS'
res.header 'Access-Control-Allow-Methods', 'GET, OPTIONS'
# try: 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'
res.header 'Access-Control-Allow-Headers', 'Content-Type'
# ...
似乎不起作用看来我的浏览器(Chrome)没有发送初始的OPTIONS请求。当我刚刚更新资源块时,我需要提交一个跨源GET请求:
It doesn't seem to work. It seems like my browser (Chrome) is not sending the initial OPTIONS request. When I just updated the block for the resource I need to submit a cross-origin GET request to:
app.get "/somethingelse", (req, res) ->
# ...
res.header 'Access-Control-Allow-Origin', '*'
res.header 'Access-Control-Allow-Credentials', true
res.header 'Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS'
res.header 'Access-Control-Allow-Headers', 'Content-Type'
# ...
它可以(在Chrome中)。这也适用于Safari。
It works (in Chrome). This also works in Safari.
我已经读过...
在执行CORS的浏览器中,每个跨源GET或POST请求之前都有一个OPTIONS请求,用于检查GET或POST是否正常。
In a browser implementing CORS, each cross-origin GET or POST request is preceded by an OPTIONS request that checks whether the GET or POST is OK.
所以我的主要问题是,我的情况怎么会不会发生?为什么我的app.options块不是调用的?为什么我需要在主应用程序块中设置标题?
So my main question is, how come this doesn't seem to happen in my case? Why isn't my app.options block called? Why do I need to set the headers in my main app.get block?
推荐答案
为了回答您的主要问题,CORS规范如果POST或GET中有任何非简单的内容或标题,则只需要在POST或GET之前进行OPTIONS调用。
To answer your main question, the CORS spec only requires the OPTIONS call to precede the POST or GET if the POST or GET has any non-simple content or headers in it.
请参阅 https://developer.mozilla.org/En/HTTP_access_control
这篇关于如何允许CORS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!