januw a
januw a

Reputation: 2248

Nestjs sets both http and https servers

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

Upvotes: 3

Views: 18107

Answers (2)

Samira
Samira

Reputation: 81

async function bootstrap() {
  const httpsOptions = {key: fs.readFileSync(SSL_KEY_PATH, 'utf8'), 
  cert: fs.readFileSync(SSL_CERTIFICATE_PATH, 'utf8')};

  const app = await NestFactory.create(AppModule,{httpsOptions});
  await app.listen(process.env.PORT);
}
bootstrap();

Upvotes: 2

DanDuh
DanDuh

Reputation: 540

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();

Upvotes: 4

Related Questions