Sunday, April 9, 2017

Laravel can't return true json response

I have a quite simple Laravel controller:

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

When I try to open a corresponding url in browser(I use Google Chrome) it works fine. There is {"a":"hello"} response and content type is application/json.

But when I receive data via javascript (I use fetch polyfill) I see that content type is text/html. I checked it in GoogleChrome DevTools and within my code:

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

    })
    .catch(function(error){

    });

Well I've got the error - Unexpected token < in JSON at position 0.

I completely don't understand what's happened.

PS:

Laravel version - 5.4, PHP Version 7.0.15, XAMPP 3.2.2

Fetch polyfill version - 2.0.3

Google Chrome version - 57.0.2987.133

And yes, it sounds strange, but in MS Edge v.20.10240 it works fine.



via Sergey

Advertisement