【问题标题】:Laravel API returns Invalid JSONLaravel API 返回无效的 JSON
【发布时间】:2018-02-13 12:34:17
【问题描述】:

routes/api.php 我创建了以下路线

Route::get('/config', function(){
    return response()->json([
        'cdn' => cdn_url(),
        'slide_image_path' => '/uploads/front-slides/',
        'offer_image_path' => '/uploads/offers/',
        'offer_image_thumb_path' => '/uploads/offers/thumbs/'
    ]);
});

在浏览器中,我正在做

$.ajax({
    url : 'https://www.example.com/api/config',
    success : function(response){
        var data = JSON.parse(response);
        console.log(data);
    }
});

并收到错误“位置 1 处 JSON 中的意外标记 o”; 但是当我使用核心 php 的 json_encode() 时,json 响应被成功解析。

当我使用https://jsonformatter.curiousconcept.com/ 来验证 JSON 无论我使用什么(json_encode()response()->json()),它都可以毫无问题地解析 JSON。但它也给出了关于无效 JSON 的警告。

到目前为止,我观察到当我使用json_encode() 时,响应包含一个标头“内容编码:gzip”。 但是当我使用 Laravel 的response()->json() 时,header Content Encoding: gzip 是不存在的。

我还尝试在使用response()->json() 时使用header('Content-Encoding: gzip') 函数手动设置此标头。但随后浏览器给出错误“net::ERR_CONTENT_DECODING_FAILED”;

我认为这是与内容编码或字符编码有关的问题。

【问题讨论】:

  • 不用解析,直接使用

标签: json laravel rest character-encoding content-encoding


【解决方案1】:

您的回复似乎没有任何问题。问题在于您在接收/解析数据时。

尝试使用stringify方法:

$.ajax({
    url : 'https://www.example.com/api/config',
    success : function(response){
        var data = JSON.parse(JSON.stringify(response));
        console.log(data);
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    • 2016-03-13
    • 1970-01-01
    • 2018-11-17
    • 2017-09-05
    • 2020-01-12
    相关资源
    最近更新 更多