Laravel 无法 return 正确 json 响应
Laravel can't return true json response
我有一个非常简单的 Laravel 控制器:
class MyController extends Controller
{
public function list()
{
return response()->json(['a' => 'hello']);
}
}
当我尝试在浏览器中打开相应的 url 时(我使用 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
Google Chrome 版本 - 57.0.2987.133
是的,这听起来很奇怪,但在 MS Edge v.20.10240 中它工作正常。
您需要将请求的内容类型 json 设置为 header。我不知道 polyfill,但这就是我使用 jquery
的方式
$.ajax({
type: 'GET',
url: url,
contentType: 'application/json; charset=utf-8',
success:
error:
});
我尝试对所有路线使用 session
身份验证。所以,问题就在那里。
api
如下路线对我有帮助:
Route::middleware('auth:api')->get('/list', 'ApiController@list');
再想想。我为 here.
中描述的所有请求添加了 api_token
我有一个非常简单的 Laravel 控制器:
class MyController extends Controller
{
public function list()
{
return response()->json(['a' => 'hello']);
}
}
当我尝试在浏览器中打开相应的 url 时(我使用 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
Google Chrome 版本 - 57.0.2987.133
是的,这听起来很奇怪,但在 MS Edge v.20.10240 中它工作正常。
您需要将请求的内容类型 json 设置为 header。我不知道 polyfill,但这就是我使用 jquery
的方式 $.ajax({
type: 'GET',
url: url,
contentType: 'application/json; charset=utf-8',
success:
error:
});
我尝试对所有路线使用 session
身份验证。所以,问题就在那里。
api
如下路线对我有帮助:
Route::middleware('auth:api')->get('/list', 'ApiController@list');
再想想。我为 here.
中描述的所有请求添加了api_token