使用 ExpressJS 处理 pre-flight 请求

Serving pre-flight request using ExpressJS

我使用下面的代码在 express 中创建了一个简单的路由。

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

app.get('/route1', (req, res) => {
  res.send({ data: "Route 1" });
});

app.listen(3000);

当我 运行 curl -X GET http://localhost:3000/route1 时,我得到 {"data":"Route 1"} 作为响应。

但是,我尝试 运行ning curl -X OPTIONS http://localhost:3000/route1 来模拟 CORS pre-flight 请求。我收到了 GET,HEAD 作为回复。

我找不到任何支持此行为的文档。为什么上面的路由响应了OPTIONS请求?

(注意:我没有使用任何其他软件包,例如 CORS

编辑

根据 Quentin 的回答,我尝试发出另一个 OPTIONS 请求,其中包含相关 headers 并在 curl 中显示 headers 标志。

curl -i -X OPTIONS http://localhost:3000/route1 \
    -H 'Access-Control-Request-Method: POST' \
    -H 'Access-Control-Request-Headers: content-type,x-requested-with'
HTTP/1.1 200 OK
X-Powered-By: Express
Allow: GET,HEAD
Content-Type: text/html; charset=utf-8
Content-Length: 8
ETag: W/"8-ZRAf8oNBS3Bjb/SU2GYZCmbtmXg"
Date: Wed, 03 Jul 2019 11:14:07 GMT
Connection: keep-alive

GET,HEAD

OPTIONS 是 standard HTTP method with standard behaviour that has built-in support in Express.

CORS 规范在常规 OPTIONS 请求之上添加了额外的语义。

curl -X OPTIONS http://localhost:3000/route1 发出一个 OPTIONS 请求,但它不是模拟一个预战请求(因为它缺少一堆 CORS 规范要求的请求 headers)。您对该请求的响应也不包含任何 CORS 响应 header。


重新编辑:

I tried issuing another OPTIONS request with relevant headers

您错过了 Origin header,但如您所见,由于您没有在 Express 应用中设置 CORS 支持,响应仍然不包含任何 CORS 响应headers.