NestJS 设置返回headers
在使用 NestJS 开发应用程序时,经常需要设置返回给客户端的响应头部信息。响应头部信息包括了一些元数据,比如内容类型(Content-Type)、授权信息(Authorization)等等。在 NestJS 中,我们可以很方便地设置返回的响应头部信息。
1. 基本用法
在 NestJS 中,设置返回的响应头部信息非常简单。只需要在控制器中的方法上使用 @Res()
装饰器,然后通过 response
对象设置响应头即可。
import { Controller, Get, Res } from '@nestjs/common';
import { Response } from 'express';
@Controller('cats')
export class CatsController {
@Get()
findAll(@Res() res: Response): string {
res.header('custom-header', 'hello world');
return 'This action returns all cats';
}
}
在上面的示例中,我们通过 res.header('custom-header', 'hello world')
方法设置了一个自定义的响应头部信息,键为custom-header
,值为hello world
。
2. 设置多个响应头信息
有时候我们需要设置多个响应头信息,可以通过链式调用 res.header()
方法来实现。
import { Controller, Get, Res } from '@nestjs/common';
import { Response } from 'express';
@Controller('cats')
export class CatsController {
@Get()
findAll(@Res() res: Response): string {
res
.header('custom-header1', 'value1')
.header('custom-header2', 'value2');
return 'This action returns all cats';
}
}
3. 删除响应头信息
有时候我们需要删除指定的响应头信息,可以通过 res.removeHeader()
方法实现。
import { Controller, Get, Res } from '@nestjs/common';
import { Response } from 'express';
@Controller('cats')
export class CatsController {
@Get()
findAll(@Res() res: Response): string {
res.header('custom-header', 'hello world');
res.removeHeader('custom-header');
return 'This action returns all cats';
}
}
在上面的示例中,我们设置了一个自定义的响应头信息后,立即通过 res.removeHeader('custom-header')
方法删除了该响应头信息。
4. 设置跨域响应头信息
在实际开发中,我们经常需要设置跨域请求的响应头信息,比如允许的域名、请求头、请求方法等。可以通过 res.header()
方法设置以下跨域响应头信息:
import { Controller, Get, Res } from '@nestjs/common';
import { Response } from 'express';
@Controller('cats')
export class CatsController {
@Get()
findAll(@Res() res: Response): string {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
return 'This action returns all cats';
}
}
在上面的示例中,我们设置了跨域请求的响应头信息,允许所有域名访问,允许的请求方法为GET、PUT、POST、DELETE、OPTIONS,允许的请求头为 Origin、X-Requested-With、Content-Type、Accept。
总结
通过本文的介绍,我们学习了在 NestJS 中如何设置返回的响应头部信息。我们可以通过 @Res()
装饰器获取到响应对象,然后使用 res.header()
方法设置相应的响应头信息。这样我们可以根据需求设置任意的响应头信息,包括自定义头部信息、跨域响应头信息等。