简体   繁体   中英

Node.js (Openshift) express response not working

I am using OpenShift and Node.js I am trying to get the average - rating for each result but I cant get the response to work even though the console reports correctly. I get 3.9454323 into the console , but when I git localhost:3002/getM/1 the response is blank.

app.get('/getM/:movieId', function(request,response) {
  var movieId = request.params.movieId;
  var connection = mysql.createConnection({
    host: process.env.OPENSHIFT_MYSQL_DB_HOST || 'localhost',
    user: process.env.OPENSHIFT_MYSQL_DB_USERNAME || 'root',
    password: process.env.OPENSHIFT_MYSQL_DB_PASSWORD || '',
    port: process.env.OPENSHIFT_MYSQL_DB_PORT || '3306',
    database: 'test'
  });
  connection.connect(function (err) {
    if (err) {
      console.error('error connecting: ' + err.stack);
      response.send("error connecting to database");
      return;
    }
    console.log('connected as id ' + connection.threadId);
  });
  connection.query('SELECT * FROM `ratings` WHERE `movieId` = ?',[movieId], function(err, result) {
    if (err) {
      response.send(err);
    }
    var sum = 0;
    result.forEach(function(movie) {
      sum += movie["rating"];
      console.log(sum);
    });
    console.log(sum/result.length);
    response.send(sum/result.length);
  });
});

You are passing a numeric argument to response.send() . Here's what the express documentation says:

res.send([body])

Sends the HTTP response.

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

see: http://expressjs.com/api.html

Try this:

response.send( "" + sum/result.length );

EDIT: BTW, if you're using an older version of express, then express may be trying to interpret the number as an HTTP status code. I'm not sure what express will do with floating point values, but in any case that's clearly not what you intended.

Finally when a Number is given without any of the previously mentioned bodies, then a response body string is assigned for you. For example 200 will respond will the text “OK”, and 404 “Not Found” and so on.

see: http://expressjs.com/3x/api.html#res.send

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