How to know if a request is http or https in node.js

前端 未结 9 1237
别跟我提以往
别跟我提以往 2020-12-08 04:11

I am using nodejs and expressjs. I wonder if there is something like request.headers.protocol in the clientRequest object. I would like to build the baseUrl for

9条回答
  •  暖寄归人
    2020-12-08 04:21

    For pure NodeJS (this works locally and deployed, e.g. behind Nginx):

    function getProtocol (req) {
        var proto = req.connection.encrypted ? 'https' : 'http';
        // only do this if you trust the proxy
        proto = req.headers['x-forwarded-proto'] || proto;
        return proto.split(/\s*,\s*/)[0];
    }
    

提交回复
热议问题