首页 > 解决方案 > cookie 没有在 nextjs 中发送到服务器

问题描述

我有一个 nextjs 应用程序,我在后端使用 expressjs 和 graphql。在我的 ssr 页面上,我正在做:

export async function getServerSideProps(ctx) {
    const id = ctx.query.slug[1]
    const ad = await fetchCarAd(id, ctx)

    return {
        props: {
            .
            .
            .
        },
    }
}

fetchCarAd 终于来到了这里:

    const response = await axios(getGraphqlUrl, {
        data: data,
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        withCredentials: true,
    })

在后端我正在做:

const canBookmarkAd = async (parent, args, context) => {
    const user = await ejectUserFromReq(context)
    .
    .
    .
}
export const ejectUserFromReq = async (context) => {
    const token = context.cookies && context.cookies.token ? context.cookies.token : null
    if (!!!token) {
        return null
    }
    .
    .
    .
}

即使我可以在 chrome 开发人员工具 > 应用程序 > 存储中看到 cookie,或者当我从其他下一页导航到此页面时,这里的 cookie 也是空的。

但是如果我从 nextjs 上下文中弹出 cookie 并作为标题传递给 axios,它工作正常。

    // here ctx is comming from nextjs.
    const cookie = ctx ? ctx.req.headers.cookie : null;
    const response = await axios(getGraphqlUrl, {
        data: data,
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'CSRF-Token': getCsrfTokenFromDom(),
            'Cookie': cookie || ''
        },
        withCredentials: true,
    })

此解决方案有效,但给我们以下错误:

在此处输入图像描述

因为 cookie 是一个禁止的标头名称

这只发生在getServerSideProps中。如果我在 cookie 工作正常之后发送请求并且不需要将 cookie 添加到 headername。

任何人都知道为什么 cookie 是空的,或者在getServerSideProps中发送 cookie 的正确方法是什么?

标签: javascriptexpressnext.js

解决方案


推荐阅读