javascript - 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 的正确方法是什么?
解决方案
推荐阅读
- javascript - 带括号的 JavaScript 正则表达式不起作用
- javascript - 如何制作mat-tree组件Angular Material 6.0.1
- sql - 具有最大日期和多个条件的 SQL 查询
- python - 如何根据 DataFrame 中的下一个周期观察过滤观察
- c# - EF6 从数据库返回错误数据
- php - 正确读取和编辑包含编码 HTML 和 HTML 编码特殊字符的 csv 文件
- python - 资源需求流程是否分为多个流程?
- delphi - 如何在 Firemonkey 中最大化对齐/调整 5 个矩形的大小?
- android - 编译问题(在 tissot_sprout 上)
- python - 使用 Python request.get 参数,但它给了我错误的 url