Node.js (Openshift) express response not working - javascript

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

Related

Why does the order of my gets change how the program works?

I encountered a weird bug when doing a quick coding assignment.
Here is my code.
Lets call this 'A'
//Grab all the animals from the database
WebApp.get('/all',(req,res) =>
{
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '1234', //Enter your password here
// I found that mySQL 8.0 uses a new default authent plugin whereas 5.7 uses a different one, If you get a ER_NOT_SUPPORTED_AUTH_MODE error from the response, try referring to this post to alter your root password. (https://stackoverflow.com/questions/50373427/node-js-cant-authenticate-to-mysql-8-0)
database: 'animals'
});
const query = "SELECT * FROM animals";
connection.query(query, (err, rows, fields) =>
{
if (err)
{
console.error('error : ' + err.stack);
res.sendStatus(500);
return;
}
console.log("Fetched animals successfully");
//console.log(rows); // Use this for error checking to see if a authent problem occurs.
res.json(rows);
});
});
and this 'B'
//Grab a selected animal from the database given a valid Id.
WebApp.get('/:id',(req,res) =>
{
console.log("Fetching user with id: " + req.params.id);
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '1234', //Enter your password here
// I found that mySQL 8.0 uses a new default authent plugin whereas 5.7 uses a different one, If you get a ER_NOT_SUPPORTED_AUTH_MODE error from the response, try referring to this post to alter your root password. (https://stackoverflow.com/questions/50373427/node-js-cant-authenticate-to-mysql-8-0)
database: 'animals'
});
const animalId = req.params.id;
const query = "SELECT * FROM animals WHERE id = ?";
connection.query(query, [animalId], (err, rows, fields) =>
{
if (err)
{
console.error('error : ' + err.stack);
res.sendStatus(500);
return;
}
console.log("Fetched animals successfully");
//console.log(rows); // Use this for error checking to see if a authent problem occurs.
res.json(rows);
});
});
For some reason, if I put A before B it works, and I get successful results from my queries. However, if I put B before A, B will return successfully, but A will return '[]'. Anyone know why?
Thanks for any help!
Have you tried terminating the connection after each request, or considered using a connection pool? I am not familiar with nodeJS integration with MySQL, but in SQLServer, it is best to use ConnectionPool, when asynchronously making database requests.

How to display data from MySQL into HTML-Page with NodeJS

I'm new in Node JS and I'm trying to display the fetched data from my MySQL Table into a table in my HTML-File. But I couldn't find anything that helped me. I would really appreciate it if somebody can help me to get a solution! :)
Here's my js-code:
//app.js
// Get the mysql service
var mysql = require('mysql');
var express = require('express');
var app = express();
app.get('/', function (request , response) {
fetchData(response);
console.log('Done. Displayed Data.');
});
// Add the credentials to access your database
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'Breunninger',
port: '3306'
});
// connect to mysql
connection.connect(function(err) {
if(err){throw err;}
console.log('Connected');
});
function executeQuery(sql, cb){
connection.query(sql, function( result, fields){
cb(result);
})
}
function fetchData(response){
executeQuery("SELECT username, tor, datum, sendungsstruktur FROM Buchung JOIN user ON(user.id = Buchung.userid)", function (result) {
console.log(result);
response.write('<div class="container-wrap"><table id="example" class="display"><tr>');
for(var column in result[0]){
response.write('<td> <label>' + column + '</label></td>');
response.write('</tr>');
}
for(var row in result){
response.write('<tr>');
for(var column in result[row]){
response.write('<td>' + result[row][column]+ '</td>');
}
response.write('</tr>');
}
response.end('</table></div>');
});
}
<div class="container-wrap">
<div class="flexslider">
<script src="app.js"></script>
</div>
</div>
There's a small (but critical!) error in the executeQuery function, the first argument should be the error object, so if you can re-write this as below your query should work.
function executeQuery(sql, cb){
connection.query(sql, function( error, result, fields){
if (error) {
console.error("An error has occurred:", error);
} else {
cb(result);
}
})
}
Node callback usually reserve the first argument for an error object, it's easy to miss this!
Also, we should be clear, the Node.js Express code will be running on the server side, so to see the results you need to point your browser to the host and port this is serving, e.g. http://localhost:3000/ (if you do:)
app.listen(3000);

node.js - connection pooling

Hello everyone,
just wondering , is this the proper way to :
get connection from connection pool ,
send a request to mysql server,
wait for result
return the connection back to connection pool?
This below code is called everytime an user logs in, it checks his username and token, if it's a match it will open main menu page, if not it will return back to login page.
The truth is, that it's all working in Chrome, but sometimes it does not work in Firefox , it just doesn't call the connection.query() part at all..
So I'm just checking with you guys , if everything is okay with the code below..Or if there is anything I could improve or change..
var db_pool = mysql.createPool({
host: 'localhost',
user: 'dbuser',
password: 'pass',
database: 'db_name'
});
function CheckUser(username, token)
{
db_pool.getConnection(function(err, connection)
{
console.log(" [i] Getting connection from pool. ");
var entry = 0;
var query = connection.query("SELECT token FROM users where token = '"+token+"' and user_id = '"+username+"'");
query.on('result', function(data){
entry++;
});
query.on('error',
function(err){
throw(err);
}
);
query.on('end',
function()
{
if(entry == 1)
{
console.log(" [info] User ["+username+"] authorized.");
/* DO STUFF */
}else
{
console.log(" [Error] User ["+username+"] does not have token: ["+token+"].");
return false;
}
}
);
console.log(" [i] Returning back connection to pool. ");
connection.release();
});
}
Any help is greatly appreciated,
Alex
I believe that the intermittent behavior is because your release() statement is in line with the connection rather than in the 'end' handler. Here is what works for me:
var mysql = require('mysql'),
config = require('./config.json');
var pool = mysql.createPool( config );
var checkUser = function(username, token) {
pool.getConnection(function(err, connection) {
if (err) throw err;
console.log(" [i] Getting connection from pool. ");
var entry = 0,
statement = 'SELECT token FROM users where token = ? and user_id = ?',
query = connection.query( statement, [ token, username ] );
query.on('result', function(data) {
console.log( data );
entry++;
});
query.on('error', function(err) {
console.log( err );
throw err;
});
query.on('end', function() {
if (entry === 1) {
console.log(" [info] User ["+username+"] authorized.");
/* DO STUFF */
} else {
console.log(" [Error] User [", username, "] does not have token [', token, ']');
}
console.log(" [i] Returning back connection to pool. ");
connection.release();
});
});
};
console.log('check the user...');
checkUser( 'test-user', 'mytoken');
I was able to test this (with an alternate statement) with no problems. I also put the config stuff in a separate file and replaced the string statement with parameters.
Hope this helps...

node.js + MySQL & JSON-result - Callback-issue & no response to client

I'd like to use node.js to query a mySQL-database and return the results as JSON to be used in a mobile application. Unfortunately, my request just sorta times out and the server does nothing for a good 2 minutes until the log-files show my console.log()-statements.
Also, the callback doesn't return anything as result. It's just empty.
// Check dependencies
var http = require('http');
// Create the http server.
// reference: http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/
http.createServer(function(request, response) {
// Attach listener on end event.
request.on('close', function() {
console.log('request');
// run asynchronous
getSQL(function(err, result) {
console.log('json:', result);
response.writeHead(200, {
'Content-Type' : 'x-application/json'
});
// Send data as JSON string.
response.end(result);
});
});
}).listen(3000);
// Access MySQL via node-mysql
// https://github.com/felixge/node-mysql
function getSQL(callback) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'user',
password : 'pw',
database : 'db',
socketPath : '/var/run/mysqld/mysqld.sock', // socket for communication from debian <-> client, seems not to be set correcly by default?
});
connection.connect();
var json = '';
var query = 'SELECT * FROM test';
connection.query(query, function(err, results, fields) {
if (err)
return callback(err, null);
console.log('The result is: ', results[0]);
// wrap result-set as json
json = JSON.stringify(results);
});
connection.end();
callback(null, json);
};
Output after like 2 minutes:
$ node app.js
request
json:
The result is: { test: 'avc' }
json2: [{"test":"avc"}]
Based on my very basic understanding of the whole node.js-concept, my code should query the db (it does) and return a json once it's finished via the callback-function (apparently doesn't) which than is sent back as a response to the client (can't really check that since the json's empty).
I guess I made one (or a couple) major mistakes. Help and/or helpful links would be much appreciated. Thanks!
Solution, thanks to hexacyanide
// Check dependencies
var http = require('http');
// Create the http server.
// reference: http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/
/***************
* Correction 1: Using the request.on('close', function()( ... )-listener isn't required anymore
***************/
http.createServer(function(req, res) {
console.log('Receving request...');
var callback = function(err, result) {
res.writeHead(200, {
'Content-Type' : 'x-application/json'
});
console.log('json:', result);
res.end(result);
};
getSQL(callback);
}).listen(3000);
// Access MySQL via node-mysql
// https://github.com/felixge/node-mysql
function getSQL(callback) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'user',
password : 'pw',
database : 'db',
socketPath : '/var/run/mysqld/mysqld.sock', // socket for communication from debian <-> client, seems not to be set correcly by default?
});
connection.connect();
var json = '';
var query = 'SELECT * FROM test';
connection.query(query, function(err, results, fields) {
if (err)
return callback(err, null);
console.log('The query-result is: ', results[0]);
// wrap result-set as json
json = JSON.stringify(results);
/***************
* Correction 2: Nest the callback correctly!
***************/
connection.end();
console.log('JSON-result:', json);
callback(null, json);
});
};
You're following an older guide which instructs you to wait for the request's close event before sending the response, but you actually no longer need to do that.
What's happening is you aren't sending your response, so your client is timing out. Only until the client times out is when close events fires. Since the client has disconnected by the time you send your response, you don't get anything on the client and only see it in the terminal.
To fix this problem, just stop waiting for the close event and run code immediately when the request handler is called:
var http = require('http');
http.createServer(function(req, res) {
getSQL(function(err, result) {
res.writeHead(200, {
'Content-Type' : 'x-application/json'
});
res.end(result);
});
}).listen(3000);

I cannot connect to Splunk with the Javascript but can with Java

I am trying to connect to Splunk with the Javascript. I am already connecting with the Java am able to do anything that I want. When I try to connect with Javascript I keep getting a 401. I am using the same credentials for both Java and Javascript, so I know there is no issue there. My code is directly out of the examples. Here it is:
exports.main = function(opts, done) {
// This is just for testing - ignore it
opts = opts || {};
var username = opts.username || "username";
var password = opts.password || "password";
var scheme = opts.scheme || "https";
var host = opts.host || "domain.com";
var port = opts.port || "8089";
var version = opts.version || "5";
var service = new splunkjs.Service({
username: "username",
password: "password",
scheme: "https",
host: "domain.com",
port: "8089",
version: "5"
});
// First, we log in
service.login(function(err, success) {
// We check for both errors in the connection as well
// as if the login itself failed.
if (err || !success) {
console.log("Error in logging in");
console.log(err);
done(err || "Login failed");
return;
}
// Now that we're logged in, let's get a listing of all the saved searches.
service.savedSearches().fetch(function(err, searches) {
if (err) {
console.log("There was an error retrieving the list of saved searches:", err);
done(err);
return;
}
var searchList = searches.list();
console.log("Saved searches:");
for(var i = 0; i < searchList.length; i++) {
var search = searchList[i];
console.log(" Search " + i + ": " + search.name);
console.log(" " + search.properties().search);
}
done();
});
});
};
if (module === require.main) {
exports.main({}, function() {});
}
Here is the error message:
There was an error retrieving the list of saved searches: { response:
{ headers:
{ connection: 'close',
'content-length': '100',
'content-type': 'text/xml; charset=utf-8',
date: 'Tue, 20 Nov 2012 22:27:11 GMT',
server: 'Splunkd' },
statusCode: 401 },
status: 401,
data: '<response>\n<messages>\n<msg type="WARN">call not properly authenticated</msg>\n</messages>\n</response>',
error: null }
I run this on the command line with Node and get the 401 error. What else do I need to check to see what I am doing wrong.
Cross origin policy no doubt CORS
Cross-Origin policy is definitely something you want to look out as you start getting into more advanced use cases with the SDK but looking at your sample code, it looks like you unintentionally put double quotes around the variable names when instantiating the service object.
I copied your code, replaced the variable values to my server, removed the double quotes second time around and verified it through command line using node ... it worked just fine.

Categories

Resources