Nest项目设置http和https服务node
通常,咱们的项目若是不是有特别须要,是不会去考虑https的,可是在某些状况下,如,你打算把你的程序发布在微信上,就必须配置https,今天咱们就结合前面的教程,配置https。证书用的是阿里云的免费证书。express
1 证书bootstrap
我以前申请的是阿里云的免费证书,可是如今我没有找到,有别家证书更好了。ubuntu
而后下载证书api
阿里提供了Tomcat、Apache、Nginx等,这里咱们用的是Apache的,下载解压以后里面有三个文件服务器
这里面三个文件都须要用到,我刚开始配置的时候,网上的教程都是写只配置两个,实际我在运行之后,发现并不能正常访问。微信
2 项目配置app
咱们只须要配置main.ts文件便可,内容以下:async
import * as fs from 'fs'; import * as http from 'http'; import * as https from 'https'; import * as express from 'express'; import { NestFactory } from '@nestjs/core'; import { ValidationPipe } from '@nestjs/common'; import { NestExpressApplication, ExpressAdapter, } from '@nestjs/platform-express'; import { AppModule } from './app.module'; // 过滤器 import { HttpExceptionFilter } from './filters/http-exception.filter'; // 自定义拦截器 import { TransformInterceptor } from './interceptor/transform.interceptor'; // api文档插件 import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; const httpsOptions = { ca: fs.readFileSync('/opt/nestjs-api/src/ssl/nmwap.com_chain.crt'), key: fs.readFileSync('/opt/nestjs-api/src/ssl/nmwap.com.key'), cert: fs.readFileSync('/opt/nestjs-api/src/ssl/nmwap.com_public.crt'), }; async function bootstrap() { const server = express(); const app = await NestFactory.create(AppModule, new ExpressAdapter(server)); app.useGlobalFilters(new HttpExceptionFilter()); app.useGlobalInterceptors(new TransformInterceptor()); app.useGlobalPipes(new ValidationPipe()); //开启一个全局验证管道 const options = new DocumentBuilder() .setTitle('接口文档') .setDescription('系统接口文档') // 文档介绍 .setVersion('1.0.0') // 文档版本 .build(); // 为了建立完整的文档(具备定义的HTTP路由),咱们使用类的createDocument()方法SwaggerModule。此方法带有两个参数,分别是应用程序实例和基本Swagger选项。 const document = SwaggerModule.createDocument(app, options); SwaggerModule.setup('/api', app, document); await app.init(); http.createServer(server).listen(3000); https.createServer(httpsOptions, server).listen(443); } bootstrap();
这里面是所有的,httpsOptions里面的文件路径是你项目证书的路径,我这里放在opt下,打算把项目部署到ubuntu上。ide
3 运行项目
若是不会部署,那简单,你的项目文件直接放到服务器上,而后build,用node运行下main.js,此种方式关闭窗口程序就会中止运行,因此只适合测试用。
而后访问接口地址。