reactjs - 如何在 getServerSideProps 中使用 fetch 转发 cookie?
问题描述
我正在为我的应用程序使用 Nextjs。在页面上,我想从经过身份验证的 API 端点('/api/profile')获取数据。
我尝试了以下方法,但没有成功:
export async function getServerSideProps(ctx) {
const { req, res } = ctx
const cookies = cookie.parse(req.headers.cookie ?? '')
const mycookie = cookies[MY_COOKIE] // mycookie exists and is set correctly
if (mycookie) {
const response = await fetch(process.env.SERVER_HOST+'/api/profile', {
credentials: 'same-origin' // I tried with and without this, also tried "include" instead
})
...
我有两个问题:
- 有没有办法避免输入绝对 URL?(我希望简单地使用'/api/profile',因为它是一个“内部”api)
- 如何确保从 /api/profile 获取数据所需的 cookie 被转发
fetch
?
注意:我的 cookie 是httpOnly
.
解决方案
Turns out I'm allowed to manually forward the cookie through:
if (mycookie) {
const response = await fetch(process.env.SERVER_HOST+'/api/profile', {
headers: {
cookie: mycookie
}
})
...
推荐阅读
- c++ - 寻找一种加速功能的方法
- php - 为什么搜索总是重定向到最后一个 if?
- python - 使用 Python 和 Jaydebeapi 查询时间戳数据时出错
- c# - 有没有办法让 GetConversationHeight 的返回不那么慢?
- javascript - 为什么表达式与花括号一起打印?
- reactjs - 如何在反应路由器 4 中替换路由和刷新?
- java - 允许 Apache 的 FreeMarker 模板引擎从外部资源文件夹加载模板
- android - 如何通知我的应用关于服务器上新的可用资源下载?
- java - 使用 lambda 表达式时无法解析方法“split(java.lang.String)”
- crystal-reports - 如何在 Crystal Reports 上添加子组