NodeJS Express中写个中间件就可以搞定HTTP跳转HTTPS了,

app.use(function (req, res, next) {
    if(req.protocol !== 'https'){
        return res.redirect('https://' + req.hostname + req.originalUrl);
    }
    next();
});

注意上面有个return可别忘写了,不然报错!

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (/root/taobao/node_modules/express/lib/response.js:767:10)
    at ServerResponse.send (/root/taobao/node_modules/express/lib/response.js:170:12)
    at done (/root/taobao/node_modules/express/lib/response.js:1004:10)
    at tryHandleCache (/root/taobao/node_modules/ejs/lib/ejs.js:257:5)
    at View.exports.renderFile [as engine] (/root/taobao/node_modules/ejs/lib/ejs.js:480:10)
    at View.render (/root/taobao/node_modules/express/lib/view.js:135:8)
    at tryRender (/root/taobao/node_modules/express/lib/application.js:640:10)
    at Function.render (/root/taobao/node_modules/express/lib/application.js:592:3)
    at ServerResponse.render (/root/taobao/node_modules/express/lib/response.js:1008:7)

加上return就OK了

添加新评论