我试图在使用Express.js web框架的Node.js应用程序中支持CORS。我已经阅读了谷歌关于如何处理这个问题的小组讨论,并阅读了一些关于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'
  # ...

这似乎不管用。似乎我的浏览器(Chrome)没有发送最初的选项请求。当我刚刚更新了块的资源,我需要提交一个跨起源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'
  # ...

它工作(在Chrome)。这也适用于Safari。

我听说……

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

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


当前回答

/*首先,这可能是像我这样的初级开发人员的问题:确保在你的fetch方法中使用“lambda”>>>>“'”而不是“'”!* /

const response = await fetch(https://api....);

/plus,强烈推荐以下文章:https://developer.edamam.com/api/faq/

其他回答

使用CORS包。然后输入这些参数:

cors({credentials: true, origin: true, exposedHeaders: '*'})

最简单的答案是使用cors包。

const cors = require('cors');

const app = require('express')();
app.use(cors());

这将使CORS全面启用。如果你想学习如何在没有外部模块的情况下启用CORS,你真正需要的只是一些Express中间件,它可以设置“Access-Control-Allow-Origin”标头。这是允许从浏览器到服务器的交叉请求域所需的最小值。

app.options('*', (req, res) => {
  res.set('Access-Control-Allow-Origin', '*');
  res.send('ok');
});

app.use((req, res) => {
  res.set('Access-Control-Allow-Origin', '*');
});

这与Pat的回答相似,不同之处在于我用res.sendStatus(200)结束;而不是next();

代码将捕获方法类型OPTIONS的所有请求,并返回access-control-headers。

app.options('/*', (req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
    res.sendStatus(200);
});

代码接受问题中要求的所有来源的CORS。但是,最好将*替换为特定的来源,即http://localhost:8080,以防止误用。

因为我们使用的是app.options-method而不是app.use-method,所以我们不需要做这样的检查:

req.method === 'OPTIONS'

我们可以从其他答案中看到。

我在这里找到了答案:http://johnzhang.io/options-request-in-express。

前段时间,我遇到了这个问题,所以我这样做是为了在我的nodejs应用程序中允许CORS:

首先你需要使用以下命令安装cors:

npm install cors --save

现在将以下代码添加到应用程序的启动文件中,如(app.js或server.js)

var express = require('express');
var app = express();

var cors = require('cors');
var bodyParser = require('body-parser');

//enables cors
app.use(cors({
  'allowedHeaders': ['sessionId', 'Content-Type'],
  'exposedHeaders': ['sessionId'],
  'origin': '*',
  'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
  'preflightContinue': false
}));

require('./router/index')(app);

可以参考下面的代码相同。来源:Academind / node-restful-api

const express = require('express');
const app = express();

//acts as a middleware
//to handle CORS Errors
app.use((req, res, next) => { //doesn't send response just adjusts it
    res.header("Access-Control-Allow-Origin", "*") //* to give access to any origin
    res.header(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept, Authorization" //to give access to all the headers provided
    );
    if(req.method === 'OPTIONS'){
        res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET'); //to give access to all the methods provided
        return res.status(200).json({});
    }
    next(); //so that other routes can take over
})