【发布时间】:2022-01-26 13:28:43
【问题描述】:
我正在尝试从在 localhost:3000 上运行的 React 应用调用在 localhost:8000 上运行的 PHP API。经过多次尝试后,我仍然收到“CORS Preflight Did Not Succeed”错误。
我的 API 有以下标头:
if (@$_SERVER['HTTP_ORIGIN']) {
header("Origin: http://localhost:8000");
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
}
我像这样使用 fetch 调用 API(但它以某种方式发送空请求正文):
let inputData:object = {email, password}
fetch("http://localhost:8000/data/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(inputData)
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
奇怪的是,当直接从浏览器开发工具(第二张截图)或 Insomnia 等 API 客户端发送请求时,这些请求可以正常工作:
【问题讨论】:
-
Access-Control-Allow-Headers:*有帮助吗? -
@nice_dev 不幸的是,我得到了同样的错误。
-
好的,如答案中所述,服务器必须以 200 ok 状态响应 OPTIONS 请求。
标签: php reactjs api cors fetch