Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

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

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


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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...