如何允许CORS? [英] How to allow CORS?

查看:172
本文介绍了如何允许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中)。

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块?为什么我需要在我的主app.get块中设置标题?

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?

推荐答案

要回答你的主要问题,

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.

请参阅中的预先发送的请求。如果POST或GET中包含任何非简单的内容或标题,则只需要OPTIONS调用。 href =https://developer.mozilla.org/En/HTTP_access_control> https://developer.mozilla.org/En/HTTP_access_control

这篇关于如何允许CORS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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