ajck's avatar
Level 1

Javascript POST via fetch() not being received by Laravel Request?

I have a Javascript POST in the browser sending data to a Laravel (v5.4) backend. Network tab in the browser shows data sent successfully. Laravel logs show no data received. Can't see why...

Client:

    fetch('saveloaddata', {
    	method: 'POST',
    	headers: { 'X-CSRF-TOKEN': $('#IDform > input[name="_token"]').val() },
    	body: JSON.stringify(sendData),
    	keepalive: true // Ensures data gets sent even after the page closed, see https://web.dev/disallow-synchronous-xhr/#fetch-keepalive
    	});

Server: web.php

    Route::post('saveloaddata', ['middleware' => 'auth', 'uses' => 'MainController@saveloaddata']);

MyController.php

    public function saveloaddata(Request $request)
    	{
        Log::info($request->all());

Log output is: local.INFO: array ()

Data being sent is just a short JSON string. On the client in the fetch() block I've also tried without JSON.stringify, so body: sendData, - same result.

POST requests to the same URL using JQuery $.ajax() work fine. I need to use fetch() for this though because this call is to send a small amount of data (~1 - 2 Kb) when the user closes the browser, so I'm following accepted practices (responding to a visibilitychange event in the browser and I would be using navigator.sendBeacon but that uses fetch() and I needed to set keepalive:true so am just using fetch() directly).

The request is clearly getting through Laravel's auth layer as the receiving function is triggered and the logging command runs (as do others in the same code, e.g. logging the user is fine). So, what has happened to the POST data!?

Thanks

0 likes
4 replies
tykus's avatar

No problem here - you are just logging incorrectly by passing an array where a string is expected. Use the second context argument for the array of data:

Log::info('received', $request->all());

Or, stringify the payload:

Log::info(json_encode($request->all()));
ajck's avatar
Level 1

@tykus Thank you. Just tried the first one and output was: local.INFO: received

(i.e. no data)

and then the second: local.INFO: []

tykus's avatar

@ajck Bah!

What does console.log(JSON.stringify(sendData)) look like?

Please or to participate in this conversation.