Express - Nodejs - HTTPS服务器

时间:2018-04-03 09:05:03

标签: node.js express https

我在我的应用程序中使用带快递的https服务器,问题是快递从不侦听该端口,它适用于http但不适用于https

app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.use(function (error, req, res, next) {
    if (error instanceof SyntaxError) {
        res.status(400).json({
            status: 'failed',
            message: "Enter a valid JSON object."
        });
    } else {
        res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
        res.header('Expires', '-1');
        res.header('Pragma', 'no-cache');
        next();
    }
});
app.use(cors());
app.use(morgan('dev'));
require('./config/routes.js')(app);
server = https.createServer({
        key: fs.readFileSync(process.env.SSL_LOCATION+"ssl.key"),
        cert: fs.readFileSync(process.env.SSL_LOCATION+"ssl.cert")
    },app).listen(parseInt(process.env.SOCKET_PORT, 10) || 4000, '0.0.0.0',function(){
        console.log('Express server listening to port '+parseInt(process.env.SOCKET_PORT, 10) || 4000);
    });
    io = require('socket.io').listen(server);

但如果我添加

port=5455
app.listen(port);

快递开始听,但在不同的端口 有什么建议吗?

1 个答案:

答案 0 :(得分:0)

尝试用常数替换您的端口并进行测试。另外,尝试在下面运行我的代码(它基于你的代码,适合我)。如果它不能解决您的问题,请写。

const https = require('https');
const express = require("express");
const fs = require('fs');
const bodyParser = require("body-parser");
const morgan = require('morgan');

app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(morgan('dev'));

// for test
app.get('/', (req, res) => {
    res.send("Work");
})

const server = https.createServer({
        key: fs.readFileSync("./ssl.key"),
        cert: fs.readFileSync("./ssl.crt")
},app)
server.listen(8000)
io = require('socket.io').listen(server);
console.log('Start');
console.log(server.address().port);