gpt4 book ai didi

node.js - 为什么即使我的前端代码只是发出 POST 请求,浏览器也会发送 OPTIONS 请求?

转载 作者:可可西里 更新时间:2023-11-01 15:20:14 28 4
gpt4 key购买 nike

我的前端代码:

<form action="" onSubmit={this.search}>
<input type="search" ref={(input) => { this.searchInput = input; }}/>
<button type="submit">搜索</button>
</form>

// search method:
const baseUrl = 'http://localhost:8000/'; // where the Express server runs
search(e) {
e.preventDefault();
let keyword = this.searchInput.value;
if (keyword !== this.state.lastKeyword) {
this.setState({
lastKeyword: keyword
});
fetch(`${baseUrl}search`, {
method: 'POST',
// mode: 'no-cors',
headers: new Headers({
'Content-Type': 'application/json'
}),
// credentials: 'include',
body: JSON.stringify({keyword})
})
}
}

还有我的 Express.js 服务器代码:

app.all('*', (req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
// res.header('Access-Control-Allow-Credentials', true);
res.header('Content-Type', 'application/json; charset=utf-8')
next();
});

当我提交表单时,我收到了两个请求。其中一个是 OPTIONS 请求,另一个是 POST 请求,对它的响应是正确的:

two requests to /search with response codes 200 OPTIONS request to localhost:8000/search POST request to localhost:8000/search

如您所见,Express 服务器运行在 8000 端口,React 开发服务器运行在 3000 端口。localhost:3000 正在请求 localhost:8000/search ,并且 localhost:8000 正在通过使用 POST 方法请求另一个来源。但是,只有第二个请求运行良好。我不知道这是怎么发生的。当然,如果我用 querystring 发出 GET 请求,一切都是正常的。但我也想知道如何使用请求正文进行 POST 提取。

最佳答案

那个OPTIONS在尝试 POST 之前,浏览器会自动发送请求。从您的代码请求。这称为 CORS 预检。

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Preflighted_requests有详细信息。

在这个具体案例中,要点是 Content-Type: application/json代码添加的请求 header 会触发浏览器执行预检 OPTIONS请求。

因此,该特定预检请求的目的是让浏览器询问服务器,“您是否允许跨源 POST具有 Content-Type 的请求其值不是 application/x-www-form-urlencoded 之一的 header , multipart/form-data , 或 text/plain ?”

为了让浏览器认为预检成功,服务器必须发回一个 Access-Control-Allow-Headers 的响应。包含 Content-Type 的 header 在它的值(value)。

所以我看到你有 res.header('Access-Control-Allow-Headers', 'Content-Type')在您当前的服务器代码中 http://localhost:8000/ ,如果您要以这种方式手动编码,那么这是要设置的正确值。但我认为这不起作用的原因是因为您也没有显式处理 OPTIONS 的代码。请求。

要解决这个问题,您可以尝试安装 npm cors包裹:

npm install cors

...然后做这样的事情:

var express = require('express')
, cors = require('cors')
, app = express();
const corsOptions = {
origin: true,
credentials: true
}
app.options('*', cors(corsOptions)); // preflight OPTIONS; put before other routes
app.listen(80, function(){
console.log('CORS-enabled web server listening on port 80');
});

这将处理 OPTIONS请求,同时还发回正确的 header 和值。

关于node.js - 为什么即使我的前端代码只是发出 POST 请求,浏览器也会发送 OPTIONS 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46904400/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com