简体   繁体   中英

How to call an http endpoint using the `https.get(...)` method in the Node.js https library

I want to call a basic endpoint to parse the json data it exposes. The data is served up using a REST endpoint I run locally on my machine. The URL is simple and open on port 80 only (no SSL or TLS on port 443).

When I call the endpoint using the following code I get this error:

ncaught NodeError: Protocol "http:" not supported. Expected "https:"

Here is my typescript code:

var req = https.get(`http://localhost/events/recent`, (response) => {
    var responseCode;
    var responseBody = [];
    response.on("data", (data) => {
        responseBody.push(data);
    });
    response.on("end", (data) => {
        var result = Buffer.concat(responseBody);
        responseCode = response.statusCode;
        if (response.statusCode === 200) {
            processResult(result);
        }
        else {
            console.log(`The Response failed with status code: ${responseCode}`);
        }
    });
});
req.end();

Your issue is that you are using the https library. To use the http library, change the first line of your code to the following:

var req = http.get(`http://localhost/events/recent`, (response) => {

See how you originally had https , meaning that the function expected an https beginning address.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM