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

  • 5
    it looks that you write these routes inside `web` file not `api` – Joseph Apr 16 '21 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. – Tim Lewis Apr 16 '21 at 19:05
  • No I am in api.php as I said in postman its working – David Kristek Apr 16 '21 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) –  Apr 16 '21 at 19:14
  • no there are not – David Kristek Apr 16 '21 at 19:16
  • Are you using additional authorization Laravel packages such as [Sanctum](https://laravel.com/docs/8.x/sanctum) or [Fortify](https://laravel.com/docs/8.x/fortify)? or do you happen to require ANY authentication when it comes to post requests? – Mike Elahi Apr 17 '21 at 06:19
  • yes I am using Sanctum for auth, but not by this routes – David Kristek Apr 17 '21 at 07:46
  • @DaviMendesDev I figuered out, that in postman in cookies is XSRF-TOKEN with some long string value, but I have no idea I add that to fetching – David Kristek Apr 17 '21 at 09:58
  • Already found answer: here it was quite complicated, hope it will help – David Kristek Apr 17 '21 at 10:14
  • man, if it's working on postman means that you have the XSRF-TOKEN on Postman. BTW is weirdy that you are using routes from `api.php` and still need the csrf-token –  Apr 17 '21 at 16:31

1 Answers1

0

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