Javascript PHP和js获取意外令牌<;localhost中的in-JSON错误
我知道关于这个话题有几个问题。我申请了他们,但我还是犯了这个错误Javascript PHP和js获取意外令牌<;localhost中的in-JSON错误,javascript,php,ajax,fetch,Javascript,Php,Ajax,Fetch,我知道关于这个话题有几个问题。我申请了他们,但我还是犯了这个错误 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 php代码 header('Access-Control-Allow-Origin: *'); header('Content-type:application/json;charset=utf-8'); echo json_encode(['data' => 'te
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
php代码
header('Access-Control-Allow-Origin: *');
header('Content-type:application/json;charset=utf-8');
echo json_encode(['data' => 'test']);
这个意想不到的为使用fetch提供了很好的指导,特别是对于初学者
事实上,我之前也遇到过同样的问题,在搜索了几个小时之后,我运气不佳,所以我尝试了一下,最后让它工作了
我在开发者Mozilla上复制粘贴了示例代码,并在url之后为对象添加了完整的初始化值
fetch(url, {
body: JSON.stringify(data), // must match 'Content-Type' header
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, same-origin, *omit
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json'
},
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // *client, no-referrer
})
.then(response => response.json())
它成功了,所以我尝试删除每个属性,看看删除它是否会再次导致错误,我发现删除凭据:“同源会导致我之前遇到的错误
您忘记在代码上添加方法:“GET”
。您的最终代码应该如下所示。希望能有帮助
fetch('http://localhost:50/data', {
method: 'GET',
credentials: 'same-origin',
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then((response) => { return response.json(); })
.then((result) => {
console.log(result);
});
您的本地主机服务器可能抛出html错误。尝试使用浏览器的inspector并观察网络请求响应,您应该能够看到返回的内容。通常这是因为php在响应之前在html标记中给出警告或错误。我看到这是一个CORS请求。您的服务器端是否在飞行前处理CORS?(这是由内容类型标题触发的)我可以从URL获得json输出老实说,我认为在投票时至少添加一些评论会很好,我不是一个专业人士,所以任何关于我答案错误的评论都会很有帮助
fetch('http://localhost:50/data', {
method: 'GET',
credentials: 'same-origin',
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then((response) => { return response.json(); })
.then((result) => {
console.log(result);
});