Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
512 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...