Search code examples
javascriptphplaravelsveltesveltekit

Error When POST with fetch (Svelte, Laravel)


//sendWPMToServer Method

async function sendWPMToServer(wpm) {
        try {

            const currentUser = $authenticatedUser;
            if (!currentUser) {
                console.error("User is not authenticated");
                return;
            }

            const response = await fetch("http://127.0.0.1:8000/api/scores", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                credentials: "include",
                body: JSON.stringify({
                    user_id: currentUser.id,
                    wpm_score: wpm,
                }), 
            });
        } catch (error) {
            console.log("Error");
        }
    }

// api.php

Route::post('register', [AuthController::class, 'register']);
Route::post('login', [AuthController::class, 'login']);

Route::middleware('auth:sanctum')->group(function() {
    Route::get('user', [AuthController::class, 'user']);
    Route::post('logout', [AuthController::class, 'logout']);
    Route::post('scores', [ScoresController::class, 'store']);
});

// ScoreController.php

public function store(Request $request)
    {
        $userId = $request->input('user_id');
        $wpmScore = $request->input('wpm_score');

        UserScore::create([
            'user_id' => $userId,
            'wpm_score' => $wpmScore,
        ]);

        return response()->json(['message' => 'Score stored successfully'], 201);
    }

// Javascript - Fetch Postman

myHeaders.append("Content-Type", "application/json");
myHeaders.append("Cookie", "jwt=1%7CEHYsf3eIO3X82iyeDwJunfnXcR2E1x1eQNPgkbFH078daa05");

var raw = JSON.stringify({
  "user_id": 1,
  "wpm_score": 60
});

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("http://127.0.0.1:8000/api/scores", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

Postman Image postman

i want to make typing game test, and when the game is over and wpm is calculated i want to send the WPM to server which is i use laravel for the REST API, but i got the 500 Intrenal Server Error and i cant send the WPM to server, but when i test it with Postman its work without error

i have tried to changes the fetch code but anything doesnt work, i want to send the wpm to database so i can use it to make the leaderboard


Solution

  • If you are using CSRF protection in the form then you should pass the CSRF token in the request headers of the JS code

    Try:

     const csrfToken = document.querySelector('meta[name="csrf-token"]').content;
     myHeaders.append("X-CSRF-TOKEN", csrfToken);