admin管理员组文章数量:1427548
I have created /sign-in
endpoint that basically returns object with 2 tokens - refresh token and access token.
@Post('/sign-in')
signIn(@Body() signInUserDto: SignInUserDto): Promise<TokensDto> {
return this.userService.signIn(signInUserDto);
}
What I want to do, is to send access token normally as JSON
, but send access token as cookie, so I changed a little bit this function and made it look like this.
@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 });
}
As a result, I get access token in response, but I don't get refresh token in cookie. Right away I can tell, that on front-end I have withCredentials: true
in axios. Also, when I send request to this endpoint with postman, I get cookie, but not on front-end. Why it happens and how I can make it set cookie?
PS.
In server terminal, no matter how I send request, from front-end or postman, I get this warning:
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
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)
I have created /sign-in
endpoint that basically returns object with 2 tokens - refresh token and access token.
@Post('/sign-in')
signIn(@Body() signInUserDto: SignInUserDto): Promise<TokensDto> {
return this.userService.signIn(signInUserDto);
}
What I want to do, is to send access token normally as JSON
, but send access token as cookie, so I changed a little bit this function and made it look like this.
@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 });
}
As a result, I get access token in response, but I don't get refresh token in cookie. Right away I can tell, that on front-end I have withCredentials: true
in axios. Also, when I send request to this endpoint with postman, I get cookie, but not on front-end. Why it happens and how I can make it set cookie?
PS.
In server terminal, no matter how I send request, from front-end or postman, I get this warning:
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./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)
Share
Improve this question
edited Aug 12, 2022 at 4:59
dokichan
asked Aug 12, 2022 at 4:52
dokichandokichan
6514 gold badges22 silver badges59 bronze badges
7
-
How are you checking if you have the cookie on the front end? Have you checked the response headers for a
Set-Cookie
header? – Jackie McDoniel Commented Aug 12, 2022 at 4:53 - I check it in Application/Cookies in devtools. – dokichan Commented Aug 12, 2022 at 4:55
- What about the response headers? – Jackie McDoniel Commented Aug 12, 2022 at 5:39
-
@JayMcDoniel Actually, nothing, but here you go.
Connection: keep-alive Content-Length: 282 Content-Type: application/json; charset=utf-8 Date: Fri, 12 Aug 2022 06:24:20 GMT ETag: "ho9ctu0n8u7u" Keep-Alive: timeout=5 Vary: Accept-Encoding
– dokichan Commented Aug 12, 2022 at 6:24 - 1 Okay, that sounds like an issue with Next not forwarding on the cookie, not that Nest (or rather express) isn't sending the cookie in the first place – Jackie McDoniel Commented Aug 12, 2022 at 6:32
1 Answer
Reset to default 3I was able to solve this problem, but only partly.
The problem was with front-end, not back-end, because, as I said before, I was able, using postman, to get cookie from server.
And here is the issue.
First of all, you need to install 2 packages cookie
and @types/cookie
, than, in route (as we remember, routing in Next.js
works as folder structure in project), you need to import serialize from installed 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);
}
}
And as a result, in response, you can see Set-Cookie
header with cookie, but, that's why it resolved partly, I don't see this cookie in devtools in Application/Cookies
section.
本文标签: javascriptCannot set cookie with NestjsStack Overflow
版权声明:本文标题:javascript - Cannot set cookie with Nest.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745500850a2661022.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论