Response.data returning json data as string Laravel 8/Axios

Viewed 4425

In my laravel controller i'm returning a response as below

return response()->json([
                'name' => 'Abigail',
                'state' => 'CA',
            ], 400);

When i make a call from a browser using Axios the data I get back is showing the json object as a string

enter image description here

doing json.parse(response.data) also returns Unhandled Rejection (SyntaxError): Unexpected token in JSON at position 0

I'm using Laravel 8

the content-type is application/json and so is accept. Is there something that needs to be included?

For the Axios call i have a class called User which contains this static login method enter image description here

The login method is then called inside another file enter image description here

1 Answers

use

JSON.parse(data);

to convert it to JavaScript object.

Also I think your return statement inside the controller adds some spaces at the beginning of the json string. Try below code to make sure you remove any possible space additions:

return response()->json(['name' => 'Abigail','state' => 'CA'], 400);
Related