简体   繁体   中英

Get json response to axios from laravel controlller

So I am making axios post request to Laravel controller:

 return axios.post('/create',
   {
     data: {...currentSettings},
   },
   {
     headers: {
         'Accept': 'application/json'
   }}).then(response => {
          console.log(response.data);
   });

And Controller should return json response:

return response()->json([
     'data' => $data,
]);

But somehow in response I receive text/html
![在此处输入图像描述
And also Response headers says this:
在此处输入图像描述

Cant find solution to fix this.. Would appreciate some help

I think you need to await for the response.json() and then console.log your data accordingly.

return axios.post('/create',
   {
     data: {...currentSettings},
   },
   {
     headers: {
         'Accept': 'application/json'
   }}).then(async response => {
      const data = await response.json();
      console.log(data. Data)
   });

Look at that: You have double

data

Because your code:

return response()->json([
     'data' => $data,
]);
basic response of laravel has data and you and one data property => data.data

You don't need to add header when use axios To get data from controller like this;

 console.log(response.data.data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM