首页 > 解决方案 > 使用 Fetch 获取 API POST

问题描述

我正在做一个项目,我在 JS 中有一个异步函数调用 PHP 函数,但由于某种原因,即使我觉得语法正确,它也会不断抛出我的错误函数。

这是JS:

async function UpdateBlog() {
    var test = "test";
    const settings = {
        method: 'POST',
        body: JSON.stringify({
            blog: test
        }),
        headers: {
            'Content-Type': 'application/json',
        }
    };
    var thisurl = baseurl;
    const response = await fetch(thisurl, settings);
    document.getElementById("scratch").innerHTML = await response.json();
}

这就是在 PHP 中捕获它的原因

if ($_SERVER["REQUEST_METHOD"] == "POST"){
  if(isset($_POST["blog"])){
    UpdateBlog($_POST["blog"]);
  } 
  else {
    RequestFail();
  }

function RequestFail(){
  http_response_code(404);
  header('Content-Type: application/json');
  echo json_encode(false);
}

我已经将“UpdateBlog”PHP 函数作为 GET 进行了测试,它可以工作,所以这不是问题

编辑:弄清楚第一个 if... 语句正在被触发,但似乎 $_POST["blog"] 显示为空

标签: javascriptphpasync-await

解决方案


如果 fetch 是一个“thenable”函数,最好使用

const result = ''
fetch(thisurl, settings).then(
  (result) => {response = result;}
)


推荐阅读