Michel Gisenaël
Michel Gisenaël

Reputation: 174

Laravel can't get data sent from axios FormData in Nuxt

I tried to sent api request from Nuxt to Laravel. On my nuxt i have axios configured like this:

export default function({$axios, store}, inject){
  var base_url = "http://api-test.test/api";
  inject('api', function(){
      const axios_api = $axios.create()
      axios_api.setBaseURL(base_url);
      axios_api.setHeader('Accept', 'application/json', 'common');
      axios_api.setHeader('Content-type', 'application/json', 'common');
      return axios_api;
  });
}

And my post request is :

var formData = new FormData();
formData.append('name','name');
formData.append('lastname','lastname');
this.$api().post('/image', formData).then(response => {
     console.log(response.data)
})

And on my laravel controller i have:

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

Here is my route:

Route::post('/image', [ImageController::class, 'index']);

This response return an empty array, but when i use object

var data = { name: 'name', lastname: 'lastname' }

The response return my data; it's if my formData is not sent on the request

My console.log from using formData FormData My console.log from using simple object object I trie to put multipart/form-data on header when calling axios

const config = {
    headers:{'Content-Type' : 'multipart/form-data'}
};
this.$api().post('/image', formData, config).then(response => {
     console.log(response.data)
})

There is no effect at all.

I used FormData cause i want to upload file.

I use laragon (if it make any difference)

--------------------WHAT I NOTICED---------------------

I installed axios (i used @nuxtjs/axios before), i tested it, i can get the formdata sent to laravel and i can treat my file now; I don't know if @nuxtjs/axios can't send formdata but standard axios work well.

Upvotes: 0

Views: 645

Answers (1)

Sparkle123
Sparkle123

Reputation: 17

For form-data fist check if cors is not blocking the request, and also make sure that you include a csrf token to your form-data or maybe disable csrf check on that specific route.

Put this in the form:

<meta name="csrf-token" content="{{ csrf_token() }}">

Get the csrf in js:

const csrf = document.querySelector('meta[name="csrf-token"]')['content'];

Then append it to your form:

axios_api.setHeader('X-CSRF-TOKEN', csrf);

Upvotes: 0

Related Questions