我想学习fetch的工作原理。后台非常简单
<?php
print_r(json_encode($_POST['test']));
我创建了这个fetch
fetch('http://localhost/test.php', {
method: 'POST',
body: JSON.stringify({
test: 'test'
})
})
.then(res => res.json())
.then(data => console.log(data))
这段代码一直在console.log中返回null。我哪里出错了?
你有两个问题
string和Fetch
如果你使用fetch
发送一个字符串,它将默认发送一个Content-Type: text/plain
头。
纯文本不是JSON。请输入正确的Content-Type
fetch('http://localhost/test.php', {
method: 'POST',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
test: 'test'
})
})
PHP不会自动处理JSON格式的请求
您需要阅读原始主体并自己解析它。这是常见问题解答。这就是解决办法。