【问题标题】:Laravel Sanctum Breeze with Next JSLaravel Sanctum Breeze 与 Next JS
【发布时间】:2022-01-03 11:23:16
【问题描述】:

我刚刚安装了这个https://github.com/laravel/breeze-next 存储库,并且正如预期的那样,一切正常,如记录的那样。登录、注销和注册工作正常。

现在登录后,我想保护 API 路由,但是当我在登录后尝试访问受保护的路由时,它会抛出 401 错误。

这里是 Repo 中给出的 AXIOS 设置,

import Axios from 'axios'

const axios = Axios.create({
    baseURL: process.env.NEXT_PUBLIC_BACKEND_URL,
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
    },
    withCredentials: true,
})

export default axios

我刚刚用 Axios 用 \api\test 添加了一个服务器调用

export async function getStaticProps() {
    const response = await axios.get(`/api/test`);
  
    return {
        props: {
            customers: response.data
        },
    }
  }

这是 laravel 中的 API。

Route::middleware(['auth:sanctum'])->get('/test', function () {
    return response()->json([
        'val' => 1,
        'msg' => 'successfully',
    ]);
});

如果我删除中间件,它工作正常。但是添加中间件auth sanctum时,总是显示401错误。

Server Error
Error: Request failed with status code 401

This error happened while generating the page. Any console logs will be displayed in the terminal window.

所以我可以在 SPA 中使用 sanctum 进行身份验证?

【问题讨论】:

    标签: laravel axios next.js


    【解决方案1】:

    您是否已将 sanctum 添加到您的 kernel.php 中?

    默认情况下,您的 Kernel.php 中的 \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, 被注释掉了。

    应该是这样的:

        'api' => [
            \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    

    【讨论】:

    • 是的,它已经被添加并且默认情况下与 Breeze 一起使用
    • @rjcode 你正在运行:php artisan serve 或通过可卡容器?
    • 使用工匠命令。
    【解决方案2】:

    我遇到了同样的问题,而是使用getStaticProps 函数,我能够使用useEffect() 使用回购协议提供的 axios 设置解决,因此您可以尝试这种方式。 假设您的目录结构 pages/test.js,在您的情况下是:

    
    import axios from "../lib/axios";
    import {useEffect, useState} from "react";
    import AppLayout from "../components/Layouts/AppLayout";
    
    const Test = () => {
        const [customers, setCustomers] = useState()
       
        useEffect(() => {
            axios
                .get("/api/tests")
                .then((response) => {
                    setCustomers(response.data);
                })
                .catch((error) => console.error(error));
        }, []);
    
        return (
            <AppLayout
                header='Customers'
            >
    
                <Head>
                    <title>Customers</title>
                </Head>
    
                <div className="py-12">
                    <div className="max-w-7xl mx-auto sm:px-6 lg:px-8">
                        <div className="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                            <div className="p-6 bg-white border-b border-slate-200">
                                {customers.map((customer, index) => (
                                    <div key={customer.val}>
                                        <div>
                                            {customer.val}
                                            {customer.message}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                </div>
            </AppLayout>
        )
    
    }
    

    如果您需要在此目录结构test/[id].js 中使用相同的方法创建详细视图:

    
    import axios from "../../lib/axios";
    import AppLayout from "../../components/Layouts/AppLayout";
    import Head from "next/head";
    import {useEffect, useState} from "react";
    import {useRouter} from "next/router";
    
    const Profiles = () => {
        const [customer, setCustomer] = useState()
    
        // Use router to get the id from the url your visiting
        const router = useRouter();
    
        useEffect(() => {
            if(!router.isReady) return;
            axios
                .get(`/api/tests/${router.query.id}`) // Here we accessing the url parameter from useRouter()
                .then((response) => {
                    setCustomer(response.data);
                })
                .catch((error) => console.error(error));
        }, [router.isReady]);
    
        return (
            <AppLayout
                header='Customer'
            >
    
                <Head>
                    <title>Customer</title>
                </Head>
    
                <div className="py-12">
                    <div className="max-w-7xl mx-auto sm:px-6 lg:px-8">
                        <div className="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                            <div className="p-6 bg-white border-b border-slate-200">
                                <div>
                                    {customer.val}
                                    {customer.message}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </AppLayout>
        )
    }
    
    

    学分:

    【讨论】:

      猜你喜欢
      • 2022-09-27
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 2020-12-31
      • 2021-09-20
      • 2021-08-06
      • 1970-01-01
      相关资源
      最近更新 更多