gpt4 book ai didi

javascript - Laravel 无法返回真实的 json 响应

转载 作者:行者123 更新时间:2023-11-28 04:47:20 25 4
gpt4 key购买 nike

我有一个非常简单的 Laravel Controller :

class MyController extends Controller
{
public function list()
{
return response()->json(['a' => 'hello']);
}
}

当我尝试在浏览器中打开相应的网址(我使用 Google Chrome)时,它工作正常。有{"a":"hello"}响应和内容类型为 application/json .

但是当我通过 javascript 接收数据时(我使用 fetch polyfill ),我看到内容类型是 text/html 。我在 GoogleChrome DevTools 和我的代码中检查了它:

fetch("/list")
.then(function(response) {
console.log(response.headers.get('Content-Type')); // => 'text/html'
return response.json();
})
.then(function(json) {

})
.catch(function(error){

});

嗯,我收到错误 - Unexpected token < in JSON at position 0 .

我完全不明白发生了什么。

PS:

Laravel 版本 - 5.4、PHP 版本 7.0.15、XAMPP 3.2.2

获取polyfill版本 - 2.0.3

谷歌浏览器版本 - 57.0.2987.133

是的,这听起来很奇怪,但在 MS Edge v.20.10240 中它工作得很好。

最佳答案

您需要将请求的 header 设置为 json 内容类型。我不知道polyfill,但这就是我用jquery 做到的方式

 $.ajax({
type: 'GET',
url: url,
contentType: 'application/json; charset=utf-8',
success:
error:
});

关于javascript - Laravel 无法返回真实的 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43241212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com