【发布时间】:2021-07-23 15:52:38
【问题描述】:
我正在尝试解析通过在我的自定义快递服务器上包含属性 httpOnly: true 设置的 cookie
现在在我的 NextJs 应用程序中,我可以在服务器端方法 getServerSideProps 中获取 cookie,并从那里访问 ctx.req.cookies 中的 cookie。但是当我对自定义服务器进行 fetch api 调用(从服务器端方法)时,自定义服务器 api 调用中似乎无法访问 cookie。
这是我在server.ts 中的express 配置:
// Express Configuration
app.set('port', process.env.PORT || 3000)
app.use(cors({ credentials: true, origin: true }))
app.use(cookieParser())
app.use(passport.initialize())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
这就是我在自定义快递服务器上设置 cookie 的方式:
res.cookie('rtk', refreshTokenJWT.token, {
httpOnly: true,
})
这是来自 getServerSideProps 方法的 fetch api 调用:
const response = await fetch('http://localhost:3000/refresh_token', {
credentials: 'include',
method: 'POST',
})
也许是因为我必须使用绝对 url 进行 api 调用,当我尝试执行 fetch('/refresh_token', ...) 时,我收到错误:TypeError: Only absolute URLs are supported
我可以从request body 中的服务器端方法发送有效负载并在自定义快递服务器中处理它,但这似乎不是最好的解决方案。
请帮忙,在此先感谢。
编辑:澄清一下,await fetch() 发生在 nextjs 的服务器端方法 getServerSideProps 中。
按照@O 的建议,在fetch api 调用中将cookie 作为标头发送。琼斯有效,但我的印象是这行不通,因为我设置了httpOnly: true。
【问题讨论】:
-
请通过editing 澄清您的问题:您的
await fetch()调用是在您的节点/快递代码中,而不是您的客户端代码中吗?如果是这样,请检查此。 stackoverflow.com/questions/34815845/… -
stackoverflow.com/questions/34815845/… 工作得很好。您能否将其发布为答案,以便我接受。谢谢你。 @O.Jones
标签: node.js express cookies next.js