我试图使用NestJS和cookie解析器在响应对象中发送cookie。
我的预期结果是将cookie附加到响应对象并发送给客户端(在本例中是postman)。我的实际结果是我得到了这个错误:
web-api_1 | [Nest] 152 - 02/26/2022, 1:15:52 AM ERROR [AccountController] res.cookie is not a function
web-api_1 | TypeError: res.cookie is not a function
web-api_1 | at AccountController.<anonymous> (/app/dist/apps/web-api/webpack:/ourRepo/apps/apis/web-api/src/app/account/account.controller.ts:51:13)
web-api_1 | at Generator.next (<anonymous>)
web-api_1 | at fulfilled (/app/node_modules/tslib/tslib.js:114:62)
web-api_1 | at processTicksAndRejections (node:internal/process/task_queues:96:5)这是我的代码:
// at the top
import { Body, Response, Controller, Patch, Post, Request, UseFilters, UseGuards, Put, Get } from '@nestjs/common';
// later...
@UseGuards(LocalAuthGuard)
@Post('account/sign-in')
async login(@Request() req, @Response() res): Promise<any> {
console.log(43, req.user.email, req.user.id)
const jwt = await this.accountClient.signIn({ email: req.user.email, userId: req.user.id });
const refreshToken = await this.accountClient.generateRefreshToken({email: req.user.email, ipAddress: req.ip})
const cookieOptions = {
httpOnly: true,
expires: new Date(Date.now() + 15*60*1000)
}
res.cookie('refreshToken', refreshToken, cookieOptions);
console.log(45, jwt)
return res.send(jwt);
}我不明白我做错了什么。查看this guy's code,您可以看到它对他是正确的;OP和一个助手讨论了他的问题,他们发现他的代码工作正常。我已经尽可能地复制了他的代码格式。我看不出有什么问题。
编辑: main.ts以显示我正确导入了cookieParser
/**
* This is not a production server yet!
* This is only a minimal backend to get started.
*/
import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import compression from 'fastify-compress';
import multipart from 'fastify-multipart';
import * as cookieParser from 'cookie-parser'; // <----- cookie parser used correctly
import { ClusterService } from '@repo/svc-interfaces';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter({
maxParamLength: 400
}));
app.enableCors();
app.use(cookieParser()); // <----- cookie parser used correctly
await app.register(multipart);
await app.register(compression);
const port = process.env.PORT || 3333;
await app.listen(port, '0.0.0.0');
Logger.log(
` Application is running on: http://localhost:${port}`
);
}
if (environment.production) {
ClusterService.clusterize(bootstrap);
} else {
bootstrap();
}发布于 2022-02-26 01:59:29
我搞清楚出了什么问题。我意识到有快递NestJS和时尚NestJS。我想我从那个线程复制的代码是用于Express的,所以我在googled上搜索了"fastify nestjs发送cookie“并得到了以下页面:
https://docs.nestjs.com/techniques/cookies
解决方案是npm install fastify-cookie并遵循文档。
我改为使用他们在文档中描述的setCookie方法。
一切都很好。
https://stackoverflow.com/questions/71273388
复制相似问题