简体   繁体   中英

REST API call using nodejs on localhost

I have made a REST API using R language.

#* @get /mean
normalMean <- function(samples=10){
  data <- rnorm(samples)
  mean(data)
}

I started the R server and tested the API using the url- http://localhost:8000/mean and it is working.

However when I tried to invoke the API using nodejs it returns an error:

Error: socket hang up
at TLSSocket.onHangUp (_tls_wrap.js:1124:19)
at TLSSocket.g (events.js:292:16)
at emitNone (events.js:91:20)
at TLSSocket.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)

Here is the nodejs code:

var https = require('https');
var optionsget = {
host : 'localhost', // here only the domain name
// (no http/https !)
port : 8000,
path : '/mean', // the rest of the url with parameters if needed
method : 'GET' // do GET
};

console.info('Options prepared:');
console.info(optionsget);
console.info('Do the GET call');

var reqGet = https.request(optionsget, function(res) {
console.log("statusCode: ", res.statusCode);
// uncomment it for header details
//  console.log("headers: ", res.headers);


res.on('data', function(d) {
    console.info('GET result:\n');
    process.stdout.write(d);
    console.info('\n\nCall completed');
});

});

I am not understanding where I am going wrong. I intend to make a put request in a similar manner after this.

It means that socket does not send connection end event within the timeout period. If you are getting the request via http.request (not http.get ). You have to call request.end() to finish sending the request.

https.get('http://localhost:8000/mean', (resp) => {
console.log("statusCode: ", res.statusCode);

    let result = 0;

    // on succ
    resp.on('data', (d) => {
        result = d;
    });

    // on end
    resp.on('end', () => {
        console.log(result);
    });

}).on("error", (err) => {
    console.log("Error: " + err.message);
});

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