【发布时间】:2022-12-10 16:29:25
【问题描述】:
我正在使用 nest js 并希望在用户点击特定端点时设置 cookie:
@Get()
setCookiesApi(@Res({ passthrough: true }) response:Response) {
response.setCookie('key', 'value')
}
此代码有效,cookie 设置在 Chrome 中 Application 选项卡的 cookies 存储中。如果我尝试使用 post 设置 cookie:
@Post()
setCookiesApi(@Res({ passthrough: true }) response:Response) {
response.setCookie('key', 'value')
}
我在 UI 上的代码:
try {
const response = await axios.post(
`http://localhost:3000/api/v1/hello`,
user,
{
method: 'post',
headers: {
withCredentials: true,
},
data: user,
},
);
if (response.data) {
// sss
}
} catch (err) {
if (err instanceof AxiosError) {
if (err.response) {
toast.error(err.response.data.message);
}
}
}
main.js 文件
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('api/v1');
app.useGlobalPipes(new ValidationPipe());
app.use(cookieParser());
app.enableCors({ origin: 'http://127.0.0.1:5173', credentials: true });
await app.listen(3000);
}
bootstrap();
...然后 cookies 存储为空且未设置 cookie。
问题:为什么get 请求有效但post 无效,如何解决?
【问题讨论】:
-
你如何提出要求?
-
@Konrad,我在我的问题中添加了一个简短的代码。
-
@Konrad,我将 Vite 网址更改为
http://localhost:5173/,它可以正常工作,但不能与http://127.0.0.1:5173/一起使用 -
这是出乎意料的,我不知道。您可以问另一个问题,例如“为什么 cookie 对
localhost有效,但对127.0.0.1无效?”,您可能会获得更多关注并得到答案