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,此種方式關閉窗口程序就會中止運行,因此只適合測試用。
而後訪問接口地址。