nestjs做接口转发
两种方式
一、接口做重定向
// 注解@Redirect的方式
@Post('upload')
@Redirect(otherUrl, 307)
upload() {
// 此处是为了逃避lint检查
return {url: otherUrl, statusCode: 307 };
}
// 使用res.redirect进行转发
@Post('upload')
upload(@Res() res) {
return res.status(307).redirect(otherUrl);
}
上面两种方式都是可以的,这里要注意两点:
- 重定向的地址要为客户端可以访问的地址
- 状态码尽量为307。因为301,302会把post请求改为get请求
二、服务代理
服务代理是在服务应用上面进行设置,类似于express的app.use
。此处以platform-fastify
平台的nestjs为例:
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({
logger: false
}),
);
// fastify通过app.register的方式注册插件
app.register(require('@fastify/http-proxy'), {
upstream: otherUrl,
prefix: '/proxy' //本地的路由
});
//其他设置
}
上面主要用到了@fastify/http-proxy
插件,其中的prefix
代表由这些路由开头的,都会代理到otherUrl上。
例如: upstream: 'www.service1.com', prefix: '/service1',这个时候,访问本地的localhost:80/service1/get,就会代理到www.service1.com/get
第二种方式的好处就是代理的地址可以是内部的,但此时的服务可能主要功能就是代理,如果和业务功能相互掺杂在一起,就会显得比较杂乱。
注:如果使用的是platform-express平台的nestjs服务,可参看http-proxy
、http-proxy-middleware
等插件