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

前端 未结 9 1205
别跟我提以往
别跟我提以往 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:25

    If you are using request module and for example want to know what protocol does some www use, you can use: response.request.uri.protocol

    request(YOUR_TARGET, function(error, response, body){
        if (error){
            console.log(error);
        }
        else {
            console.log(response.request.uri.protocol); // will show HTTP or HTTPS
        }
    });
    

    If you need user protocol then use request.headers.referer.split(':')[0]; just like @Harsh gave you.

    0 讨论(0)
  • 2020-12-08 04:35

    req.secure is a shorthand for req.protocol === 'https' should be what you looking for.

    If you run your app behind proxy, enable 'trust proxy' so req.protocol reflects the protocol that's been used to communicate between client and proxy.

    app.enable('trust proxy');

    0 讨论(0)
  • 2020-12-08 04:40

    If you are using Proxy Server such as Nginx you should set proxy_set_header X-Forwarded-Proto https; in its config file, so if you are using TSL express could recognize https as req.headers['x-forwarded-proto'] value or true for req.secure

    0 讨论(0)
提交回复
热议问题