2
votes

I have some problem with receiving JSON data from vuex with axios in my Laravel Backend.

I have vuex store like this, and I want to send it to backend on click.

 order: {
        delivery_id: null,
        user_id: null,
        is_active: true,
        bill: null,
        name: null,
        surname: null,
        father_name: null,
        phone: null,
        payment_type: 'cash',
        delay: null,
        cashback_paid: null,
        card: null,
        payment_screenshot: null,
        cart: null,
    }

In vue component I have this method:

sendOrder() {
  let order = this.$store.state.order.order;
  console.log(order)

  axios
    .post('/api/products', order, {
      header: {
        'Content-Type': 'application/json'
      }
    })
    .then((response) => {
      console.log(response);
    })
    .catch((error) => {
      console.log(error);
    })
}

And this is my pretty simple Laravel Controller:

$test = json_decode($request->getContent(), true);

$test = $test['payment_type'];

return response($test);

But when I'm doing this POST request, I'm receiving empty data in response.

Also, I've tried to check my API with Postman, and it's working fine. I just send request, then go to F12 > Network > find my request and copy Request Payload source data. Then I've pasted it into Postman body (raw, json) and make request with this data to same url (http://localhost:8000/api/orders), and its return 'cash' as expected. So I decided, that it's vue.js or axios problem, but I have no idea how to fix that. Thank you!

UPDATED I already have tried to remove Content-Type from axios, JSON.stringify order and had the same result - empty data on response.

1

1 Answers

0
votes

I think, before you use order in axios you should stringify the JSON data:

let order = JSON.stringify(this.$store.state.order.order);

Second part of the answer after some comments:

Are you sure about the routes file? I would call the controller from the web.php file (same folder) with a declared function (for example mytest), like this:

Route::post('/api/products', 'ProductController@mytest');

and put your controller logic in that function:

public function mytest()
{
    $test = json_decode($request->getContent(), true);
    $test = $test['payment_type'];
    return response($test);
}

If that doesn't work (also in combination with JSON.stringify), my only idea is a typo in your "pretty simple Laravel Controller" ;)...