[英]Cannot set cookie with Nest.js
我創建了/sign-in
端點,它基本上返回帶有 2 個令牌的 object - 刷新令牌和訪問令牌。
@Post('/sign-in')
signIn(@Body() signInUserDto: SignInUserDto): Promise<TokensDto> {
return this.userService.signIn(signInUserDto);
}
我想要做的是將訪問令牌正常發送為JSON
,但將訪問令牌作為 cookie 發送,所以我對這個 function 進行了一些更改,並使它看起來像這樣。
@Post('/sign-in')
async signIn(
@Request() req: ExpressRequest,
@Response() res: ExpressResponse
): Promise<ExpressResponse<any, Record<string, any>>> {
const { _at, _rt } = await this.userService.signIn(req.body);
res.cookie('_rt', _rt, {
httpOnly: true,
sameSite: 'strict',
maxAge: 7 * 24 * 60 * 60 * 1000
});
return res.status(200).json({ _at });
}
結果,我得到了訪問令牌作為響應,但我沒有在 cookie 中得到刷新令牌。 我馬上就可以看出,在前端我有withCredentials: true
in axios。 此外,當我使用 postman 向此端點發送請求時,我得到了 cookie,但不是在前端。 為什么會發生,我怎樣才能讓它設置 cookie?
PS。
在服務器終端中,無論我如何從前端或 postman 發送請求,我都會收到以下警告:
Error [ERR_INTERNAL_ASSERTION]: This is caused by either a bug in Node.js or incorrect usage of Node.js internals.
Please open an issue with this stack trace at https://github.com/nodejs/node/issues
at assert (internal/assert.js:14:11)
at ServerResponse.detachSocket (_http_server.js:223:3)
at resOnFinish (_http_server.js:685:7)
at ServerResponse.emit (events.js:314:20)
at onFinish (_http_outgoing.js:735:10)
at onCorkedFinish (_stream_writable.js:673:5)
at afterWrite (_stream_writable.js:490:5)
at afterWriteTick (_stream_writable.js:477:10)
at processTicksAndRejections (internal/process/task_queues.js:83:21)
我能夠解決這個問題,但只是部分解決。
問題出在前端,而不是后端,因為正如我之前所說,我能夠使用 postman 從服務器獲取 cookie。
這就是問題所在。
首先,您需要安裝 2 個包cookie
和@types/cookie
,然后在路由中(我們記得, Next.js
中的路由作為項目中的文件夾結構),您需要從安裝的 package 中導入序列化:
import { NextApiRequest, NextApiResponse } from "next";
import { AxiosError } from "axios";
import { api } from "../../../api";
import { serialize } from 'cookie'
export default async (
req: NextApiRequest,
res: NextApiResponse
) => {
try {
const { data } = await api.post('/user/sign-in', req.body)
res.setHeader('Set-Cookie', serialize('_rt', data.data._rt, {
httpOnly: true,
sameSite: 'strict',
maxAge: 7 * 24 * 60 * 60 * 1000
}))
return res.json(data)
} catch (error) {
return res
.status((error as AxiosError).response?.status as number)
.json((error as AxiosError).response?.data);
}
}
結果,作為響應,您可以看到帶有 cookie 的Set-Cookie
header,但這就是它部分解決的原因,我在Application/Cookies
部分的 devtools 中看不到這個 cookie。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.