0

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.

1 Answer 1

1

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);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the reply. I'm actually a newbie in nodejs. I tried changing the request to http.get also. And, tried calling request.end() also. Still stuck with the same error. Can you help me with where the changes need to be made for calling request.end()
@UjjwalGupta are you using the Plumber package?
Thanks it worked. And yes I'm using plumber package in R to expose the mean function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.