简体   繁体   English

I have installed a node based API from https://github.com/opentok/interactive-broadcast-api, but how to enable HTTPS on this API?

[英]I have installed a node based API from https://github.com/opentok/interactive-broadcast-api, but how to enable HTTPS on this API?

Normally, I use https.createServer method to server my node application over HTTPS, but in this case, I am not sure.通常,我使用 https.createServer 方法通过 HTTPS 为我的节点应用程序提供服务,但在这种情况下,我不确定。

Apparently this is the code,显然这是代码,

INDEX.JS索引.JS

'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _config = require('./config/config');

var _config2 = _interopRequireDefault(_config);

var _express = require('./config/express');

var _express2 = _interopRequireDefault(_express);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// config should be imported before importing any other file
var debug = require('debug')('ibs-backend:index');

// make bluebird default Promise
Promise = require('bluebird'); // eslint-disable-line no-global-assign

// module.parent check is required to support mocha watch
// src: https://github.com/mochajs/mocha/issues/1912
if (!module.parent) {
  // listen on port config.port
  _express2.default.listen(_config2.default.port, function () {
    debug('server started on port ' + _config2.default.port + ' (' + _config2.default.env + ')');
  });
}

exports.default = _express2.default;
module.exports = exports['default'];
//# sourceMappingURL=index.js.map

config/express.js配置/express.js

import express from 'express';
import expressJwt from 'express-jwt';
import logger from 'morgan';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import compress from 'compression';
import methodOverride from 'method-override';
import cors from 'cors';
import httpStatus from 'http-status';
import expressWinston from 'express-winston';
import expressValidation from 'express-validation';
import helmet from 'helmet';
import winstonInstance from './winston';
import routes from '../server/routes/index.route';
import config from './config';
import APIError from '../server/helpers/APIError';

const app = express();

if (config.env === 'development') {
  app.use(logger('dev'));
}

/* Define the routes that work without a JWT token */
const allowedPaths = [
  '/api/auth/token',
  '/api/auth/token-fan',
  '/api/auth/token-celebrity',
  '/api/auth/token-host',
  '/api/event/get-events-by-admin',
  '/api/event/get-current-admin-event'
];

// parse body params and attache them to req.body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressJwt({ secret: config.jwtSecret }).unless({ path: allowedPaths }));
app.use(cookieParser());
app.use(compress());
app.use(methodOverride());

// secure apps by setting various HTTP headers
app.use(helmet());

// enable CORS - Cross Origin Resource Sharing
app.use(cors());

// enable detailed API logging in dev env
if (config.env === 'development') {
  expressWinston.requestWhitelist.push('body');
  expressWinston.responseWhitelist.push('body');
  app.use(expressWinston.logger({
    winstonInstance,
    meta: true, // optional: log meta data about request (defaults to true)
    msg: 'HTTP {{req.method}} {{req.url}} {{res.statusCode}} {{res.responseTime}}ms',
    colorStatus: true // Color the status code (default green, 3XX cyan, 4XX yellow, 5XX red).
  }));
}

// mount all routes on /api path
app.use('/api', routes);

// if error is not an instanceOf APIError, convert it.
app.use((err, req, res, next) => {
  if (err instanceof expressValidation.ValidationError) {
    // validation error contains errors which is an array of error each containing message[]
    const unifiedErrorMessage = err.errors.map(error => error.messages.join('. ')).join(' and ');
    const error = new APIError(unifiedErrorMessage, err.status, true);
    return next(error);
  } else if (!(err instanceof APIError)) {
    const apiError = new APIError(err.message, err.status, err.isPublic);
    return next(apiError);
  }
  return next(err);
});

// catch 404 and forward to error handler
app.use((req, res, next) => {
  const err = new APIError('API not found', httpStatus.NOT_FOUND);
  return next(err);
});

// log error in winston transports except when executing test suite
if (config.env !== 'test') {
  app.use(expressWinston.errorLogger({
    winstonInstance
  }));
}

// error handler, send stacktrace only during development
app.use((err, req, res, next) => // eslint-disable-line no-unused-vars
  res.status(err.status).json({
    message: err.isPublic ? err.message : httpStatus[err.status],
    stack: config.env === 'development' ? err.stack : {}
  })
);

export default app;

Normally, I can use letsencrypt ssl with nodejs applications like this通常,我可以将letsencrypt ssl与这样的nodejs应用程序一起使用

const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('Hello!\n');
}).listen(443);

But in this particular scenario, I cant understand, how to do it.但是在这种特殊情况下,我不明白该怎么做。

This is the github repository这是github 存储库

Thanks for your replies in advance.感谢您提前回复。

You could pass the express app instance to https.createServer() , since express was meant to be used this way.您可以将express应用程序实例传递给https.createServer() ,因为 express 旨在以这种方式使用。

// We need to import https!
const https = require("https");
// Or, like this
import https from "https";
// Define the key and certificate.
const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};
// Then...
https.createServer(options, app).listen(443);

It should work the same as any other express app.它应该与任何其他快递应用程序一样工作。

Here is a link for more information on that: https://expressjs.com/en/4x/api.html#app.listen这是有关更多信息的链接: https://expressjs.com/en/4x/api.html#app.listen

I have fixed this, by installing SSL through Nginx.我通过 Nginx 安装 SSL 解决了这个问题。 I have included all certificates in Nginx site configuration and it worked very well.我已在 Nginx 站点配置中包含所有证书,并且运行良好。

Thank you for your help.谢谢您的帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以将在node.js中[https://github.com/jasonjoh/node-tutorial]在此处实现的Office 365 Rest Api用作Web服务吗? - Can i use office 365 Rest Api implemented here [https://github.com/jasonjoh/node-tutorial] in node.js as a Web service? 如何从github.com以及NodeJs(https)下载文件 - How download file from github.com whith NodeJs (https) 如何在浏览器中使用“https://github.com/ovvn/dom-to-pdf” - How can I use `https://github.com/ovvn/dom-to-pdf` in a Browser node.js中的核心模块如何工作? (https://github.com/nodejs/node/blob/master/lib) - How do the core modules in node.js work? (https://github.com/nodejs/node/blob/master/lib) 是否可以使用node-smpp(https://github.com/farhadi/node-smpp)发送批量短信? - Is it possible to send bulk sms with node-smpp (https://github.com/farhadi/node-smpp)? 如何使用 NodeJs 在 https://api.linkedin.com/mediaUpload/ 上放置媒体 - How to PUT media on https://api.linkedin.com/mediaUpload/ with NodeJs 按照https://github.com/liferay/alloy-ui的指示进行npm install错误 - npm install error while following instructions from https://github.com/liferay/alloy-ui 在 HTTPS 中从 Node JS 调用 Java REST API(在 Tomcat 上) - Calling Java REST API (on Tomcat) from Node JS in HTTPS 如何处理“已弃用,请使用https://github.com/pillarjs/path-to-regexp”消息 - how to deal with “DEPRECATED use https://github.com/pillarjs/path-to-regexp” message 使用 HTTPS 从不同的域向节点 API 发出请求 - Making requests to a node API from a different domain using HTTPS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM