[英]Can't send appropriate cookies to API server with Next.js
I've an API express server hosted on api.mydomain.com and a Next.js website hosted on mydomain.com, my Next.js application makes a getServerSideProps
request to my API to get page data that I want to display. I can set cookies for api.mydomain.com but I can't send them back to the express API, I can only send cookies stored in mydomain.com, how do I properly set cookies that my API can use?
服務器配置:
const app = express()
app.use(cookieParser())
app.use(cors({
origin: true,
credentials: true
}))
Cookie-set 路由配置:
res.cookie('language', req.params.lang, { expires: new Date(2025, 11) })
數據獲取路由配置:
router.get('/lang/:lang', async (req, res) => {
try {
const content = await PageContent.find({ language: (req.params.lang.toLowerCase() || 'en') })
res.send(content)
} catch (error) {
console.log(error);
res.status(404).send()
}
})
Next.js配置:
export async function getServerSideProps(context) {
const resContent = await fetch('api.mydomain.com/content/lang/' +
(context.req.cookies.language || 'en'), {
credentials: 'include'
})
const contents = await resContent.json()
}
為了回答我自己的問題,我在我的 Cookie-set 路由配置中設置了domain: 'mydomain.com'
選項並且它有效,不知道這是否是最佳實踐
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.