【问题标题】:Next.js / cookie is undefinedNext.js / cookie 未定义
【发布时间】:2021-08-30 01:44:16
【问题描述】:

首先:抱歉,如果这是一个不好的问题,我几周前才开始学习网络开发,现在遇到了一个我无法提出解决方案的问题。

这是一个只有基本 CRUD 功能的 next.js 应用程序(我正在关注 udemy 上的 Brad Traversys next.js 课程)

在这个组件中,我想向我的 Strapi 后端发出请求以获取用户数据

import React from 'react'
import Layout from '../components/Layout'
import { parseCookies } from '@/helpers/index'
import { API_URL } from '../../config'

const Dashboard = ({ events }) => {
    return (
        <Layout title='User Dashboard'>
            <h1>Your events</h1>
            {events && events.length && events.map((el, i) => <div>{el.name}</div>)}
        </Layout>
    )
}

export default Dashboard

export async function getServerSideProps({ req }) {
    const { token } = parseCookies(req)

    const res = await fetch(`${API_URL}/events/me`,
        {
            method: 'GET',
            headers: {
                Authorization: `Bearer ${token}`
            }
        })

    const events = await res.json()

    return {
        props: {
            events
        }
    }
}

helper 方法应该从请求中提取 cookie 并将令牌返回给 getServerSideProps

import cookie from 'cookie'


    export function parseCookies(req) {
        console.log('///// REQ IN HELPER', cookie.parse(req.headers.cookie))
        return cookie.parse(req ? req.headers.cookie || '' : '')
    }

方法返回 this 而不是令牌

{
  _xsrf: '2|07438526|dd1d3c86869ab7209b159b127acbead9|1629292796',
  'username-localhost-8888': '2|1:0|10:1629300070|23:username-localhost-8888|44:OThhNzc0YWY4MTA4NDFmZWFlYWM3MWE2MmEyNmUzYjI=|5c1a7386f172dee14bf53281f3e3ba9a6fb7e1cf067e7438529ca8f4160214f6'
}

以下是我如何设置 cookie 的示例(在这种情况下是在登录后):

import { API_URL } from '../../config/index'
import cookie from 'cookie'


export default async (req, res) => {
    if (req.method === 'POST') {
        const { identifier, password } = req.body

        const strapiRes = await fetch(`${API_URL}/auth/local`,
            {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ identifier, password })
            })

        const data = await strapiRes.json()

        if (strapiRes.ok) {

            res.setHeader('Set-Cookie',
                cookie.serialize('token', data.jwt),
                {
                    httpOnly: true,
                    maxAge: 60 * 60 * 24 * 7,
                    sameSite: 'strict',
                    path: '/'
                })

            res.status(200).json({ user: data.user })
        } else {
            res.status(data.statusCode).json({ message: data.message[0].messages[0].message })
        }
    }
    else {
        res.setHeader('Allow', ['POST'])
        res.status(405).json({ message: `Method ${req.method} is not allowed` })
    }
}

据我所知,cookie 现在应该存储在服务器端并自动放入每个请求中。据我所知,虽然我从 cookie.parse() 得到的结果是由未定义的 cookie 引起的。 在其他组件中,从标头获取 cookie 没有问题,并且可以正常工作 - 它只是在这个仪表板组件中似乎无法正常工作。

你们中有人知道如何解决这个问题吗?

【问题讨论】:

    标签: javascript cookies next.js


    【解决方案1】:

    我发现了我的错误-对于遇到此问题的其他所有人,这是我的错误: cookie.serialize 的调用错误,带有选项的对象需要是 cookie.serialize 的参数而不是 setHeader

    错误的版本

    res.setHeader('Set-Cookie',
                    cookie.serialize('token', data.jwt),
                    {
                        httpOnly: true,
                        maxAge: 60 * 60 * 24 * 7,
                        sameSite: 'strict',
                        path: '/'
                    })
    

    工作版本:

    res.setHeader('Set-Cookie',
                    cookie.serialize('token', data.jwt,
                    {
                        httpOnly: true,
                        maxAge: 60 * 60 * 24 * 7,
                        sameSite: 'strict',
                        path: '/'
                    }))
    

    【讨论】:

      【解决方案2】:

      我发现了另一个问题,可以帮助您克服这个问题。我的浏览器中保存了另一个错误的 cookie,导致我的应用程序崩溃。删除此 cookie 后一切正常

      【讨论】:

        猜你喜欢
        • 2021-03-18
        • 2022-01-06
        • 2021-10-06
        • 2021-10-17
        • 2020-03-20
        • 1970-01-01
        • 2022-01-21
        相关资源
        最近更新 更多