Express in server to perform a database query - node.js

I want to know how ExpressJS works in the server side
I need some information on Server side, Main things are,As per my knowledge,
ExpressJS can perform all the functionalists of a PHP - - - IS it
true ?
My Client(Android) is ready to submit a POST request to Server
If i can send one single information in the form of (Key,value) pair,
can the Express accept that pair- - Identify the value based on key
and, to perform a sql query to Database based on the value received
from android client?
If it can how it does it?
MY Express Program ( It gives a Response without scenario explained above - How to modify this program )
var express = require('express')
, async = require('async')
, http = require('http')
, mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: '*********',
password: "*****",
database: 'DB'
});
connection.connect();
// all environments
app.set('port', process.env.PORT || 7002);
//
//REQUEST FOR FIRST REQUEST
//
app.get('/',function(request,response){
var name_of_restaurants, RestaurantTimings;
async.series( [
// Get the first table contents
function ( callback ) {
connection.query('SELECT * FROM restaurants', function(err, rows, fields)
{
console.log('Connection result error '+err);
name_of_restaurants = rows;
callback();
});
},
// Get the second table contents
function ( callback ) {
connection.query('SELECT * FROM RestaurantTimings', function(err, rows, fields)
{
console.log('Connection result error '+err);
RestaurantTimings = rows;
callback();
});
}
// Send the response
], function ( error, results ) {
response.json({
'restaurants' : name_of_restaurants,
'RestaurantTimings' : RestaurantTimings
});
} );
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Hope I am clear
Thanks ,

You can send information via query params or as part of the url path. If you send it as a query param, you can access it using
req.query.keyName;
If you want to send the value as part of the url, you'll have to add a route to accept it. You can accept variable content in a url by using the :keyName form. Express will capture it in req.params. So it would look a little like this:
app.get('/some/url/:keyName', function(req, res, next){
var keyName = req.params.keyName;
// . . .
});
Then you can send your http request to '/some/url/someKeyValue' and the variable keyName will then be equal to whatever you add after /some/url/.
If you're POSTing data in the body of the request, access it with req.body.keyName.
EDIT: Here's an attempt at using the original code. Note that I'm still making up values and guessing at what the intent is.
var express = require('express')
, async = require('async')
, http = require('http')
, mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: '*********',
password: "*****",
database: 'DB'
});
connection.connect();
// all environments
app.set('port', process.env.PORT || 7002);
//
//REQUEST FOR FIRST REQUEST
//
app.get('/',function(request,response){
var name_of_restaurants, RestaurantTimings;
async.series( [
// Get the first table contents
function ( callback ) {
connection.query('SELECT * FROM restaurants WHERE name = ' . request.body.name, function(err, rows, fields) {
console.log('Connection result error '+err);
name_of_restaurants = rows;
callback();
});
},
// Get the second table contents
function ( callback ) {
connection.query('SELECT * FROM RestaurantTimings', function(err, rows, fields) {
console.log('Connection result error '+err);
RestaurantTimings = rows;
callback();
});
}
// Send the response
], function ( error, results ) {
response.json({
'restaurants' : name_of_restaurants,
'RestaurantTimings' : RestaurantTimings
});
} );
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
But you should really not query directly like that because of SQL injection. I've never used MySQL from node, but I'm sure there is some way to use parameterized queries. Hope this is more helpful.
Also, I'm assuming that the data will be passed in the request body, since you said you are ready to POST to the server.

Related

Why my restful API stuck when I put integer as parameter in the url using node.js

I'm trying to get data in JSON format. I just copied an old project and changed it IP address to database, username, port, password and database name.
When I try to access data through this addres: localhost:3000/&id=13
The browser just doesn't load them.
When I enter the address with the port without / I see the message with error:
return res.status(500).json({ error: "Грешна заявка. Опитай отново !"})
The same code is pinned to another database and I see the data in JSON format.
I checked 10 times if the username, password, port and database name are correct and they are fine.
The code:
// Create express app
var express = require("express")
var app = express()
var mysql = require('mysql')
var express = require("express")
var cors = require('cors')
app.use(cors())
// Server port
var HTTP_PORT = 3000
var pool = mysql.createPool({
connectionLimit: 10,
host: '192.168.0.1',
user: 'user',
port: '3388',
password: 'password',
database: 'databasename'
});
var ardaforecast = '';
app.route('/')
.get(function (req, res) {
// omitted
res.setHeader('Access-Control-Allow-Origin', '*', 'Cache-Control', 'private, no-cache, no-store, must-revalidate');
//const date = req.query.date;
const id = req.query.id;
pool.query(`CALL Get_Alert_levels_Station(${id})`, function (error, result) {
if (error)
return res.status(500).json({ error: "Грешна заявка. Опитай отново !"})
aladinModel = result;
res.json({ ardaforecast })
});
});
// Start server
app.listen(HTTP_PORT, () => {
console.log("Server running on port %PORT%".replace("%PORT%", HTTP_PORT))
});
pool.on('error', function (err) {
console.log(err.code); // 'ER_BAD_DB_ERROR'
});
app.use(function (req, res) {
res.status(404);
})
;
Can I get an example of how I can fix this or how to find out where the problem is ?
You can use this one to see how what your url contains: https://www.freeformatter.com/url-parser-query-string-splitter.html
In your example, the problem is that you're using & (ampersand), but what it does is separating multiple query parameters. Since you have just one, your url is not properly structured and does not contain any parameters whatsoever.
You should use ? (question mark) to denote the first one:
localhost:3000/?id=13
p.s. Успех ;)

How to resolve multiple queries together using Sequelizejs

I have this basic nodejs script:
var express = require('express'),
Sequelize = require('sequelize'),
promise = require('bluebird'),
app = express(),
optimus = new Sequelize('optimus', 'root', 'test', {host: '127.0.0.1', dialect: 'mysql'}),
query = 'SELECT id FROM borrowers LIMIT 0,10',
query2 = 'SELECT COUNT(*) FROM borrowers';
app.get('/', function(req,res) {
var chain = new Sequelize.Utils.QueryChainer();
console.log('begin');
chain.add(optimus, 'query', [query,null,null,[]])
.add(optimus, 'query', [query2,null,null,[]])
.run()
.success(function() {
console.log('done');
}).error(function(err) {
console.log('oh no');
});
console.log('end');
res.send('Hi Ma!');
});
var server = app.listen(3000, function() {
console.log('Listening on port %d', server.address().port);
}
);
Neither 'done' nor 'oh no' ever fires which leads me to believe that I can' chain raw queries in this manner.
What I'd really like to accomplish is to asynchronously resolve both queries and pass the results back via res.send().
I have to admit to being a complete n00b at nodejs so any insights into how to correctly structure this would be greatly appreciated.
The major issue with your code is the fact, that you are sending a response to the client/browser too early. Instead of res.send-ing at the end of the app.get method, you need to send the answer inside the success respectively inside the error callback. Here you are:
var express = require('express'),
Sequelize = require('sequelize'),
promise = require('bluebird'),
app = express(),
optimus = new Sequelize('sequelize_test', 'root', null, {host: '127.0.0.1', dialect: 'mysql'}),
query = 'SELECT id FROM borrowers LIMIT 0,10',
query2 = 'SELECT COUNT(*) as count FROM borrowers';
app.get('/', function(req,res) {
var chain = new Sequelize.Utils.QueryChainer();
console.log('begin');
chain
.add(optimus.query(query, null, { raw: true }))
.add(optimus.query(query2, null, { raw: true, plain: true }))
.run()
.success(function(results) {
res.send({
resultOfQuery1: results[0],
resultOfQuery2: results[1]
});
}).error(function(err) {
console.log('oh no', err);
});
});
var server = app.listen(3000, function() {
console.log('Listening on port %d', server.address().port);
}
);
Please notice, that I changed the credentials to my local ones. Furthermore also check the arguments of chain.add. Instead of passing the values for an upcoming serial executation, we just throw the actual asynchronous methods into it and let the querychainer handle their promises.

How can I respond in XML using ExpressJS?

I have a simple code that gives a JSON response for a specific route. Here's my current code:
var express = require('express')
, async = require('async')
, http = require('http')
, mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: '****',
password: "****",
database: 'restaurants'
});
connection.connect();
// all environments
app.set('port', process.env.PORT || 1235);
app.use(express.static(__dirname + '/public/images'));
app.get('/DescriptionSortedRating/',function(request,response){
var name_of_restaurants;
async.series( [
// Get the first table contents
function ( callback ) {
connection.query('SELECT * FROM restaurants ORDER BY restaurantRATING', function(err, rows, fields)
{
console.log('Connection result error '+err);
name_of_restaurants = rows;
callback();
});
}
// Send the response
], function ( error, results ) {
response.json({
'restaurants' : name_of_restaurants
});
} );
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
How can I make an XML response equivalent to the JSON above?
You can use any number of the XML libraries available on npm. Here's an example using the simply-named "xml" library:
var xml = require('xml');
response.set('Content-Type', 'text/xml');
response.send(xml(name_of_restaurants));
See the module's documentation for a description of how it converts JavaScript objects to XML. If you need things returned in a specific XML format, you'll have more work to do, of course.
As an update to this, it looks like res.type should be used instead as res.set does not give the same results.
res.type('application/xml');
More information can be found in the API reference.

How to perform Insert statement by decoding Base64 in express

How to decode the param values received which were received as Base64 encoded form and insert into database ?
This is what i have tried.
According to this i am getting one value recieved from the client as
param value and inserting into server ( I have recieved the request
at POST )
No base64 encoding is done here
I am using this code at present :
var express = require('express')
, async = require('async')
, http = require('http')
, mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: '******',
password: "******",
database: 'posting_information_DB'
});
connection.connect();
// all environments
app.set('port', process.env.PORT || 1234);
app.use(express.static(__dirname + '/public/images'));
app.post('/Name/',function(request,response,next){
app.use(express.bodyParser());
var keyName=request.query.Key;
var name_of_restaurants;
async.series( [
function(callback) {
connection.query('INSERT INTO details (name) VALUES (?)', [keyName], function (err, rows, fields)
{
console.log('Connection result error ' + err);
callback();
});
}
// Send the response
] );
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
What i am trying to do !
Now what changes should i need to make so that when i need recieve a
image and string as two param values
These values are Base64 encoded
How to decode these Base64 here and then insert the retrieved param
values to database
How to modify my posted Express code !
Thanks !
You can retrieve the image parameter using request.params and then create a Buffer object, specify the base64 encoding and then convert it using the .toString() method.
app.post('/Name/', function(request, response, next){
var image = new Buffer(request.params.image, 'base64').toString('binary');
// do the database insert...
});

How to get response from socket.on before calling socket.emit

I am using node.js for creating an application that is maintaing the repository for the courses and its respective lectures and slides. And the retreival of courses of student (from mysql Db) is based on student name, the retreival of lectures is based on course name and soo on. The student name is stored on server and i must get it before calling server for getting course list.
Here is my code with more explanation:
var StdName;
$(document).ready(function () {
//connect to server
connectBind();
var socket = $("#click").data();
/**********Query database For student name!!!**********/
try {
socket.emit('askStdName');
}
catch (err) {
alert(err.message);
}
/********Query database For Courses!!!************/
try {
socket.emit('view-contents', StdName);
}
catch (err) {
alert(err.message);
}
});
//connecting to server
function connectBind() {
// connect to server on this port.
var socket = io.connect('http://localhost:3000');
$("#click").data(socket);
/**********GETTING NAME OF STUDENT*********/ //I WANT TO GET STUDENT NAME BEFORE THE QUERY FOR COURSES GET CALLED
try {
socket.on('get-Studentname', function (data) {
StdName = data;
alert("StdName: " + StdName);
});
}
catch (err) {
alert(err.Message);
}
And here is the server side script:
var express = require('express'); //load express
var http = require('http'); // then http
var socketIO = require('socket.io'); // then socket
var mysql = require('mysql');
var nodemailer = require("nodemailer");
var client = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'smartboard_db'
});
client.connect();
var app = express(); // create application
var server = http.createServer(app); //create server
var io = socketIO.listen(server); // start listening to server.
io.set('log level', 2);
// setup routing for static files.
app.use(express.static(__dirname + '/public'));
//start server
server.listen(3000, function(){
console.log('Server running...');
});
// First page
app.get('/', function(request, response) {
response.sendfile(__dirname + '/student-home.html');
});
io.set('log level', 1);
io.sockets.on('connection', function (socket) {
var sucess;
console.log("client connected");
/************SENDING THE NAME TO CLIENT*************/
socket.on('askStdName', function () {
console.log('sending student name to client');
socket.emit('get-Studentname', stdName);
});
/***********CHANNEL FOR GETTING COURSE LIST************/
socket.on('view-contents', function (stdName) {
//console.log("this is what I get from client for courses: " + stdName);
var DATABASE = 'smartboard_db';
client.query('USE ' + DATABASE);
/*****QUEURY FOR COURSES *****************/
client.query('SELECT courses FROM student_info WHERE name = "' + stdName + '"', function (err, results) {
if (err) {
throw err;
}
else {
console.log(JSON.stringify({ courses: results }));
socket.emit('courses', JSON.stringify({ courses: results }));
}
});
});
});
Can ny one help please?
If the get-Studentname event should always be followed by getting the courses:
// request student name
socket.emit('askStdName');
// wait for the student name to be returned, followed by requesting the courses
socket.on('get-Studentname', function (StdName) {
socket.emit('view-contents', StdName);
});
Alternatively, you can pass a function with the request for the student name, which the server can call to send back the response (instead of having the server emit a response). This does require a different setup on your server though:
// client code
socket.emit('askStdName', function(StdName) {
socket.emit('view-contents', StdName);
});
// server code should look like this:
socket.on('askStdName', function(done) {
// get student name (depends on your setup)
...
// call the function to return the value
done(StdName);
});

Resources