我以为我以前已经解决了这个问题,并且能够通过fetch向本地托管的apache服务器发出成功的发帖请求,但是今天我尝试发帖,并且再次出现“ cors preflight request failed”错误。我不确定它为什么以前能工作,为什么突然又不能工作。
这是我三天前工作的php文件头-
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods,
Authorization, X-Requested-With');
这是我正在使用的提取请求-
fetch("http://menu.com/menu/api/post/create.php", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'title' : 'qweqweqw',
'body' : '1111w',
'author' : '2222r',
'category_id' : '2'
})
})
.then( (response) => {
console.log(response);
});
这是有效的邮递员代码:
POST /menu/api/post/create.php HTTP/1.1
Host: menu.com
Content-Type: application/json
cache-control: no-cache
Postman-Token: 83a8e0d1-f45a-4184-92f6-f0be2f8fcf5f
{
"title" : "new new title",
"body" : "new neqwsadasssssssssseqweqwew jew",
"author" : "new newzxxxxxxxxxxxxwq author",
"category_id" : "1"
}------WebKitFormBoundary7MA4YWxkTrZu0gW--
对此我将不胜感激。
编辑-
这些是cors错误:
Access to fetch at 'http://menu.com/menu/api/post/create.php' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
在我的apache服务器错误日志中,我得到了这个' PHP Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'category_id' at row 1 in /home/orphe$'
,但是由于我从邮递员那里复制/粘贴了工作请求,但仍无法正常工作,因此我不确定为什么要为category_id获取它。
答案 0 :(得分:1)
有一个预检请求(带有OPTIONS),但是服务器未返回HTTP 200 OK。
尝试将以下内容添加到create.php
:
header("HTTP/1.1 200 OK");
如果这不起作用,请同时包含请求和响应标头。
答案 1 :(得分:-1)
将我的提取请求标头更改为headers: new Headers()
可以解决所有问题。