Home > front end >  Get json response to axios from laravel controlller
Get json response to axios from laravel controlller

Time:09-13

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
![enter image description here
And also Response headers says this:
enter image description here

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

CodePudding user response:

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

CodePudding user response:

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