乐闻世界logo
搜索文章和话题

How does nestjs get the cookie in the request?

1个答案

1

In NestJS, you can retrieve cookies from requests in several ways. One common method is to use the @Req() decorator to inject the entire request object, then access the cookies via the cookies property of the request object. Here's a specific example:

typescript
import { Controller, Get, Req } from '@nestjs/common'; import { Request } from 'express'; // NestJS internally uses Express @Controller('example') export class ExampleController { @Get() getCookie(@Req() request: Request): string { const cookies = request.cookies; // Retrieve all cookies const myCookie = cookies['myCookieName']; // Access a specific cookie by name return `The value of myCookie is: ${myCookie}`; } }

Another method is to use the @Cookies() decorator. This is a custom decorator provided by NestJS that directly extracts cookies from the request. You can choose to retrieve all cookies or a specific one. For example:

typescript
import { Controller, Get, Cookies } from '@nestjs/common'; @Controller('example') export class ExampleController { @Get() getCookie(@Cookies('myCookieName') myCookie: string): string { // The `myCookie` parameter directly contains the value of the cookie named 'myCookieName' return `The value of myCookie is: ${myCookie}`; } }

In this example, the @Cookies('myCookieName') decorator injects the value of the cookie named myCookieName into the myCookie parameter.

If your NestJS application does not directly handle cookies and uses third-party libraries like Passport for authentication, these libraries often provide cookie abstraction. For instance, you might set a session cookie during login and then identify users in subsequent requests through the session.

Note that to handle cookies, you may need to install and use middleware like cookie-parser in NestJS to correctly parse cookies on the request object:

bash
npm install cookie-parser

Then, configure it in your main module or middleware:

typescript
import * as cookieParser from 'cookie-parser'; // In the configure method of the main module export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer .apply(cookieParser()) .forRoutes('*'); // Apply to all routes } }

After this, you can access cookies in your controllers as shown in the examples above.

2024年6月29日 12:07 回复

你的答案