簡體   English   中英

發布請求適用於郵遞員,但不適用於javascript提取功能

[英]Post request works in postman but not in javascript fetch function

我以為我以前已經解決了這個問題,並且能夠通過fetch向本地托管的apache服務器發出成功的發布請求,但是今天我嘗試發布一個帖子,並且再次出現“ cors preflight request failed”錯誤。 我不確定它為什么以前能工作,為什么突然又不能工作。

這是我3天前工作的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獲取此信息,因為我復制/粘貼了郵遞員的工作請求,但仍然無法正常工作。

有一個預檢請求(帶有OPTIONS),但是服務器未返回HTTP 200 OK。 嘗試將以下內容添加到create.php

header("HTTP/1.1 200 OK");

如果這不起作用,請同時包含請求和響應標頭。

將我的提取請求標頭更改為headers: new Headers()修復了所有問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM