为什么不将CORS标头添加到OPTIONS路由允许浏览器访问我的API?

扶醉桌前 提交于 2020-08-15 07:53:39

问题:

I am trying to support CORS in my Node.js application that uses the Express.js web framework. 我正在尝试在使用Express.js Web框架的Node.js应用程序中支持CORS。 I have read a Google group discussion about how to handle this, and read a few articles about how CORS works. 我已经阅读有关如何处理此问题的Google小组讨论 ,并阅读了一些有关CORS工作原理的文章。 First, I did this (code is written in CoffeeScript syntax): 首先,我做到了(代码是用CoffeeScript语法编写的):

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'
  # ...

It doesn't seem to work. 它似乎不起作用。 It seems like my browser (Chrome) is not sending the initial OPTIONS request. 看来我的浏览器(Chrome)没有发送初始的OPTIONS请求。 When I just updated the block for the resource I need to submit a cross-origin GET request to: 当我刚刚更新资源块时,我需要向以下站点提交跨域GET请求:

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'
  # ...

It works (in Chrome). 它可以工作(在Chrome中)。 This also works in Safari. 这也适用于Safari。

I have read that... 我读过...

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. 在实现CORS的浏览器中,每个跨域的GET或POST请求之前都有一个OPTIONS请求,该请求检查GET或POST是否正常。

So my main question is, how come this doesn't seem to happen in my case? 所以我的主要问题是,在我看来,这种情况怎么似乎没有发生? Why isn't my app.options block called? 为什么不调用我的app.options块? Why do I need to set the headers in my main app.get block? 为什么需要在主app.get块中设置标题?


解决方案:

参考一: https://stackoom.com/question/TehS/为什么不将CORS标头添加到OPTIONS路由允许浏览器访问我的API
参考二: https://oldbug.net/q/TehS/Why-doesn-t-adding-CORS-headers-to-an-OPTIONS-route-allow-browsers-to-access-my-API
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!