相关疑难解决方法(0)

如何允许CORS?

我试图在我的Node.js应用程序中支持使用Express.js Web框架的CORS.我已经阅读有关如何处理此问题的Google小组讨论,并阅读了一些有关CORS如何工作的文章.首先,我这样做了(代码是用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'
  # ...
Run Code Online (Sandbox Code Playgroud)

它似乎不起作用.好像我的浏览器(Chrome)没有发送初始OPTIONS请求.当我刚刚更新资源块时,我需要将跨源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'
  # ...
Run Code Online (Sandbox Code Playgroud)

它有效(在Chrome中).这也适用于Safari.

我读过......

在实现CORS的浏览器中,每个跨源GET或POST请求前面都有一个OPTIONS请求,用于检查GET或POST是否正常.

所以我的主要问题是,为什么在我的案例中似乎没有发生这种情况?为什么我的app.options块没有被调用?为什么我需要在主app.get块中设置标题?

node.js cors coffeescript express

609
推荐指数
17
解决办法
57万
查看次数

标签 统计

coffeescript ×1

cors ×1

express ×1

node.js ×1