TypeError:Cannot read properties of undefined(阅读'headers')in Next Js 13

yizd12fk  于 2023-08-04  发布在  其他
关注(0)|答案(2)|浏览(343)

我正在用redux工具包在next js 13中开发一个jwt认证系统。我有一个Django后端,它正在与我的下一个js前端通信。问题出在下一个js的API页面和redux工具包之间的通信中,以设置用户登录。下面是我在API页面中的代码:

export async function POST(request) {
    const body = await request.json();
    const { email, password } = body;
    const bodystring = JSON.stringify({
        email,
        password
    });
    console.log(`Posted data is: ${bodystring}`);
    try {
        const apiRes = await fetch(`${API_URL}/api/token/`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: bodystring
        });
        const data = await apiRes.json();
        // console.log(`Data is ${data}`)
        if (apiRes.status === 200) {
            console.log("Login Succesful")
            NextResponse.setHeader('Set-Cookie', [
                cookie.serialize(
                    'access', data.access, {
                        httpOnly: true,
                        secure: false,
                        maxAge: 60 * 30,
                        sameSite: 'strict',
                        path: '/api/'
                    }
                ),
                console.log("Access token set succesfully"),
                cookie.serialize(
                    'refresh', data.refresh, {
                        httpOnly: true,
                        secure: false,
                        maxAge: 60 * 60 * 24,
                        sameSite: 'strict',
                        path: '/api/'
                    }
                ),
                console.log("Refresh token sorted too"),
            ]);
            
            return NextResponse.json({
                // res: body
                success: 'Logged in successfully',
                status: 200,
            });
        }
} catch (error) {
        
    }
}

字符串
然后这里是我的auth.js,当用户成功登录时,它应该调度状态:

export const login = (email, password) => async dispatch => {
    const body = JSON.stringify({
        email,
        password
    });
    // alert(`body is ${body}`) //This alert is showing data hence it`s working
    dispatch({
        type: SET_AUTH_LOADING
    });
    try {
        const res = await fetch('/auth/login/api', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: body
        });
        alert(`Response is ${res}`) //There is a problem here. Check the page api
        if (res.status === 200) {
            alert("Login Succesful")
            dispatch({
                type: LOGIN_SUCCESS
            });
            dispatch(load_user());
        } else {
            alert("Login Failed")
            dispatch({
                type: LOGIN_FAIL
            });
        }
    } catch (error) {
        dispatch({
            type: LOGIN_FAIL
        });
    }

    dispatch({
        type: REMOVE_AUTH_LOADING
    });
}


当程序运行时,auth.js发送一个警报Response is [object Response],然后我在控制台中得到错误error TypeError: Cannot read properties of undefined (reading 'headers') at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:261:61) at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

mklgxw1f

mklgxw1f1#

若要修复此错误,需要在返回NextResponse对象之前初始化该对象的headers属性。您可以通过使用NextRequest对象上的headers属性作为起点来完成此操作。例如,您可以执行以下操作:

const headers = request.headers;
    const newResponse = new NextResponse({
      body: Response,
      headers,
    });

    return newResponse;

字符串

t1qtbnec

t1qtbnec2#

在进行了几次试验之后,我发现了this教程,它解释了如何使用Next 13。我意识到错误来自于没有在响应中设置头。在做了一些修改之后,下面是我在route.js中的最终代码。

export async function POST(request) {
    const body = await request.json();
    const { email, password } = body;
    const bodystring = JSON.stringify({
        email,
        password
    });
    // console.log(`Posted data is: ${bodystring}`);
    try {
        const apiRes = await fetch(`${API_URL}/api/token/`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: bodystring
        })
        const data = await apiRes.json();
        // console.log(`Data is ${data}`)
        // console.log(`Response status is:${apiRes.status}`)
        if (apiRes.status === 200) {
            console.log("Login Succesful")
            const seralized = [
                cookie.serialize(
                    'access', data.access, {
                    httpOnly: true,
                    secure: false,
                    maxAge: 60 * 30,
                    sameSite: 'strict',
                    path: '/api/'
                }
                ),
                cookie.serialize(
                    'refresh', data.refresh, {
                    httpOnly: true,
                    secure: false,
                    maxAge: 60 * 60 * 24,
                    sameSite: 'strict',
                    path: '/api/'
                }
                )
            ];
            
            const response = {
                success: 'Logged in successfully'
            };
            return new Response(JSON.stringify(response), {
                status: 200,
                headers: { "Set-Cookie": seralized },
            });
        } else {
            // console.log("Login Failed")
            return NextResponse.status(apiRes.status).json({
                error: 'Authentication failed'
            });
            
        }
    } catch (error) {
        
    }
}

字符串

相关问题