我的前端代码:
<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请求,对它的响应是正确的:
正如您所看到的,Express服务器运行在8000端口上,React开发服务器运行在3000端口上。localhost:3000
正在请求localhost:8000/search
,而localhost:8000
是通过使用POST方法请求另一个来源。但是,只有第二个请求有效。我不知道为什么会这样。当然,如果我使用查询字符串进行GET请求,一切正常。但我也想知道如何使用请求正文进行POST请求。
Access-Control-Allow-Origin
、Access-Control-Allow-Headers
和Access-Control-Allow-Method
是不够的,我必须添加Access-Control-Max-Age: 86400
才能使其工作。我猜测浏览器需要知道“访问权限”有效期多长时间的信息。 - Sasa Blagojevic