0

I'm sending Form data from a Vue component to Laravel API by POST method.

Laravel return a good response but I'm not able to manage the POST data inside the Laravel controller.

This is the client side:

 let body = JSON.stringify({
      'email': user.email,
      'password': user.password,
  });

  fetch("/login", {
         method: "POST",
         headers: new Headers({
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-CSRF-TOKEN': user.token, // NOTA: no X_CXRF-TOKEN
             body: body
                })
   })

This is the controller

namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LoginJWTController extends Controller{
  public function login(Request $request){
    print_r ($request->all());
  }
}

But the response (200 OK) is an empty array: array[]

On debug site I see the request header having:

body: {"email":"[email protected]","password":"12345678"}

Why I have no POST data in my Controller? What I'm missing?

Thanks for your help!

2
  • change this 'Content-Type': 'application/x-www-form-urlencoded' to 'Content-Type': 'application/json' and one more thing why are sending your body in headers . Commented Jun 18, 2019 at 8:50
  • Content-type it's ok, the body it's the issue! I wrote it in a bad position! lol! Commented Jun 18, 2019 at 8:59

1 Answer 1

2

Currently the body is part of your headers.

Please try this:

let body = JSON.stringify({
    'email': user.email,
    'password': user.password,
});
fetch("/login", {
     method: "POST",
     headers: new Headers({
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': user.token, // NOTA: no X_CXRF-TOKEN
     }),
     body: body
})

Also set the content type to application/json as Salman Zafar pointed out in the comments.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes! This is! I wrote it too quickly!! Fresh eyes are always welcome! Thanks for your time and caught the bug! :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.