javascript - 使用 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"] 显示为空
解决方案
如果 fetch 是一个“thenable”函数,最好使用
const result = ''
fetch(thisurl, settings).then(
(result) => {response = result;}
)
推荐阅读
- android - firebase signInWithCustomToken 不起作用
- javascript - 将字符串转换为分隔对象键
- javascript - 最大子对象 React-native
- c++ - 初始化 constexpr -“用非常量表达式非法初始化 'constexpr' 实体”
- node.js - Knex 从时间列和日期列中获取格式化时间
- java - 无法在 JPanel Java 中编辑文本区域
- reactjs - 容器中的 React 组件和 redux 的表示组件的正确分离
- python - 使用 pipenv 与 setuptools 安装 python 应用程序
- sqlite - 使用 WHERE ... IN 进行多列选择
- jquery - 当我单击一个活动选项卡时,我希望全部出现。之后,当我单击我想要的选项卡时,我希望所有其他人都消失