user3612719 user3612719 - 24 days ago 7
Javascript Question

Generate random number with Node.js page

Using Javascript node express, I'm trying to create a page that loads a random number every time. However, this sends me a 500 server error notification and I'm not sure why.

app.get('/random-number',function(req,res){
res.type('text/plain');
var randomnumber=Math.random();
res.send(randomnumber);
});

Answer

The res.send() function won't allow you to send integers in the response body.

From the Express documentation :

The body parameter can be a Buffer object, a String, an object, or an Array.

As such:

app.get('/random-number',function(req,res){
      res.type('text/plain');
      var randomnumber=Math.random();
      res.send(''+randomnumber);
});

Worked for me.

Or, of course:

app.get('/random-number',function(req,res){
      res.type('text/plain');
      var randomnumber=Math.random();
      res.send(randomnumber.toString());
});
Comments