简体   繁体   English

Axios POST 到 Laravel API 导致 419 错误,但在邮递员中工作正常

[英]Axios POST to Laravel API results in 419 error but works fine in postman

I have a new laravel project and im using Laravel sanctum api tokens to authenticate the api sending a post request with postman works fine but if i send it from my next.js project using Axios it give me a 419 error我有一个新的 laravel 项目,我使用 Laravel sanctum api 令牌来验证 api 发送邮递员的帖子请求工作正常但是如果我使用 Axios 从我的 next.js 项目发送它给我一个 419 错误

laravel project: localhost:8000 laravel 项目:本地主机:8000

next.js project: localhost:3000 next.js 项目:localhost:3000

i think its a cors proplem but i dont realy know我认为这是一个问题,但我真的不知道

laravel cors.php laravel cors.php

return [

/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/

'paths' => ['api/*', 'sanctum/csrf-cookie'],

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => false,
  ];

Update更新

api.js api.js

import Axios from "axios";

  let urls = {
  development: "http://localhost:8000/api/",
  production: "",
  };
  const api = Axios.create({
  baseURL: urls[process.env.NODE_ENV],
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
  },
  });

  export default api;

auth.js auth.js

import React, { createContext, useState, useContext, useEffect } from 

"react";
import Cookies from "js-cookie";
import Router, { useRouter } from "next/router";
//api here is an axios instance
import api from "../services/Api";

const AuthContext = createContext({});

export const AuthProvider = ({ children }) => {


 const login = async (username, password) => {
    const { data: data } = await api.post("login", {
      username,
      password,
    });
}

}

Update i tried: Why does the Laravel API return a 419 status code on POST and PUT methods?我尝试更新: 为什么 Laravel API 在 POST 和 PUT 方法上返回 419 状态代码?

i have added the routes to the VerifyCsrfToken Middleware我已经将路由添加到 VerifyCsrfToken 中间件

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'http://localhost:8000/api/login'
        //
    ];
}

same proplem i have tried commenting the Middleware same proplem同样的问题我试过评论中间件同样的问题

// \App\Http\Middleware\VerifyCsrfToken::class,

these are my routes这些是我的路线

api.php api.php

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


Route::group(['middleware' => ['auth:sanctum']], function () {

//test GRUD

   
Route::get('/posts',[PostController::class,'index']);


// logout 

Route::post('/logout',[AuthController::class,'logout']);


});

session.php i added this session.php 我加了这个

  'domain' => 'localhost',

Note: im not using sanctum csrf-cookie im using sanctum api tokens and the routes im trying to access is not even protected注意:我没有使用 sanctum csrf-cookie 我使用的是 sanctum api 令牌,我试图访问的路由甚至没有受到保护

Update get, put works fine the problem only with post request Update get, put工作正常,只有post请求才有问题

It's tough to see without your next.js auth set up but from what you have shown try changing 'supports_credentials' to true.如果没有您的 next.js 身份验证设置,很难看到,但从您所展示的内容来看,尝试将“supports_credentials”更改为 true。

Updated:更新:

I haven't used Next.js before but I have used Nuxt.我之前没用过 Next.js 但我用过 Nuxt。

You may also need to add 'SESSION_DOMAIN=localhost' to your.env file.您可能还需要将 'SESSION_DOMAIN=localhost' 添加到 your.env 文件。 You need your backend and front end to communicate on the same domain.您需要后端和前端在同一个域上进行通信。 Even if the they're on different ports.即使它们在不同的端口上。

I ran into this problem recently.我最近遇到了这个问题。 Unfortunately, I did not find the appropriate answer here after a night of searching, so I thought to drop what worked for me here.不幸的是,经过一夜的搜索,我没有在这里找到合适的答案,所以我想把对我有用的东西放在这里。

The problem is that Sanctum is trying to authenticate your frontend app like an SPA.问题在于 Sanctum 正在尝试像 SPA 一样验证您的前端应用程序。

For SPA authentication to work, the API and frontend must share the same top-level domain, which is not the case in your application and mine too.要使 SPA 身份验证起作用,API 和前端必须共享相同的顶级域,而您和我的应用程序都不是这种情况。

What I did was to stop Laravel from trying to authenticate my frontend like an SPA.我所做的是阻止 Laravel 像 SPA 一样尝试验证我的前端。 I did that by removing this class "\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class" from 'api' in my middleware group.我通过从中间件组的“api”中删除此类“\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class”来做到这一点。

You can locate the middleware group in "\app\Http\Kernel.php"您可以在“\app\Http\Kernel.php”中找到中间件组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM