0

I am trying to get data from laravel api by fetching it. In postman it`s working even with authorization with sanctum.


When I fetch with post method it gives:

Failed to load resource: the server responded with a status of 419 (unknown status) 

and then:

message: "CSRF token mismatch." ...

Here is my api routes file:

Route::post('/posts', [PostController::class, 'store']);
Route::get('/posts', [PostController::class, 'index']);
Route::get('/posts/{id}/edit', [PostController::class, 'edit']);
    
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);

And fetching:

export const addPost = async (post) => {
  let resp = await fetch(`http://127.0.0.1:8000/api/posts`, {
    method: "POST",
    body: JSON.stringify(post),
    headers: { Accept: "application/json", "Content-Type": "application/json" },
  });
  let jsData = await resp.json();
  return jsData;
};

Thanks for help

10
  • 5
    it looks that you write these routes inside web file not api Commented Apr 16, 2021 at 19:02
  • 3
    API routes should not be using CSRF tokens. If they're in routes/api.php, that is handled automatically. If you're trying to POST to a route in routes/web.php, you either need to include the CSRF token, or configure the route to not require it. Commented Apr 16, 2021 at 19:05
  • No I am in api.php as I said in postman its working Commented Apr 16, 2021 at 19:07
  • The only thing that I can think is to you verify te Postman headers to see if there's a csrf_token or something like that on headers and authorization tab (in Postman) Commented Apr 16, 2021 at 19:14
  • no there are not Commented Apr 16, 2021 at 19:16

1 Answer 1

0

if your APP_ENV is 'local' it will work in postman even if you dont put csrf token in the header..

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

Comments

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.