Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nestjs sets both http and https servers

Tags:

nestjs

I am trying to set up both http and https servers

consulted the official document

λ nest i

[System Information]
OS Version     : Windows 10
NodeJS Version : v10.16.0
NPM Version    : 6.9.0
[Nest Information]
platform-express version : 6.3.2
common version           : 6.0.0
core version             : 6.0.0

This is my main.ts file

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 { ExpressAdapter } from '@nestjs/platform-express';
import { AppModule } from './app.module';

async function bootstrap() {
  let httpsOptions = {
    key: fs.readFileSync('D:\\localhost.ssh\\ajanuw.local.key'),
    cert: fs.readFileSync('D:\\localhost.ssh\\ajanuw.local.crt'),
  };

  const server = express();
  const app = await NestFactory.create(
    AppModule, 
    new ExpressAdapter(server), // error
  );
  app.enableCors();
  await app.init();

  http.createServer(server).listen(3000);
  https.createServer(httpsOptions, server).listen(443);
}
bootstrap();

But the editor has an error message

Parameters of type "ExpressAdapter" cannot be assigned to parameters of type "AbstractHttpAdapter".    The attribute "instance" is protected, but the type "AbstractHttpAdapter" is not a class derived from "AbstractHttpAdapter".

How can I handle this error, thank you

like image 282
januw a Avatar asked Jan 29 '26 19:01

januw a


1 Answers

I think you mixing two different approaches to create the server. In your case, code should look like this:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as fs from 'fs';
import { ExpressAdapter } from '@nestjs/platform-express';
import * as http from 'http';
import * as https from 'https';
import * as express from 'express';

async function bootstrap() {
  const privateKey = fs.readFileSync('D:\\localhost.ssh\\ajanuw.local.key', 'utf8');
  const certificate = fs.readFileSync('D:\\localhost.ssh\\ajanuw.local.crt', 'utf8');
  const httpsOptions = {key: privateKey, cert: certificate};

  const server = express();
  const app = await NestFactory.create(
    AppModule,
    new ExpressAdapter(server),
  );
  await app.init();

  http.createServer(server).listen(3000);
  https.createServer(httpsOptions, server).listen(443);
}

bootstrap();
like image 106
DanDuh Avatar answered Jan 31 '26 21:01

DanDuh