I'm writing an express app that uses socket.io; however all I'm getting is the sever side telling me I'm connected, aside from that, none of my sockets are working. If anyone can tell as to why this is happening that would be greatly appreciated. Here is my code for client and server below:
Client:
var socket = new io.Socket();
socket.connect('127.0.0.1:3000');
var pageView = new pageViewModel();
pageView.setCurrentPage(pageView.getLogin());
pageView.setNav(pageView.getLogNav());
var tView = new totalViewModel();
socket.on('connection', function () {
ko.applyBindings(pageView);
function loggedIn(e) {
e.preventDefault();
var logged = {
username: document.getElementById('pEmail').value,
password: document.getElementById('pWord').value
};
socket.emit('login', JSONout(logged));
alert(JSONout(logged));
}
function signUp() {
pageView.setCurrentPage(pageView.getRegister());
pageView.setNav(pageView.getRegisterNav());
ko.applyBindings(pageView);
}
socket.on('uploadList', function (data) {
pageView.setCurrentPage(pageView.getIndex());
pageView.setNav(pageView.getIndexNav());
ko.applyBindings(pageView);
tView.setNum(JSONin(data).total);
ko.applyBindings(tView);
});
function logPurchase(e) {
e.preventDefault();
var purchObj = {
price: document.getElementById('pPrice').value,
priceName: document.getElementById('pName').value,
entryDate: new Date()
};
socket.emit('purchaseLog', JSONout(purchObj));
}
function logDeposit(e) {
e.preventDefault();
var depositObj = {
price: document.getElementById('dPrice').value,
entryDate: new Date()
};
socket.emit('depositLog', JSONout(purchObj));
}
function getLogout(e) {
e.preventDefault();
pageView.setCurrentPage(pageView.getLogin());
pageView.setNav(pageView.getLogNav());
ko.applyBindings(pageView);
socket.emit('goLogout', {
none: 'none'
});
}
function getIndex(e) {
e.preventDefault();
pageView.setCurrentPage(pageView.getIndex());
pageView.setNav(pageView.getIndexNav());
ko.applyBindings(pageView);
}
function getMonthly(e) {
e.preventDefault();
pageView.setCurrentPage(pageView.getMonthly());
pageView.setNav(pageView.getMonthlyNav());
ko.applyBindings(pageView);
}
function getYearly(e) {
e.preventDefault();
pageView.setCurrentPage(pageView.getYearly());
pageView.setNav(pageView.getYearlyNav());
ko.applyBindings(pageView);
}
socket.on('wentMonth', function (data) {
tView.setNum(total in JSONin(data));
ko.applyBindings(tView);
});
socket.on('wentYearly', function (data) {
tView.setNum(total in JSONin(data));
ko.applyBindings(tView);
});
function register(e) {
e.preventDefault();
var reg = {
username: document.getElementById('pEmail').value,
password: document.getElementById('pWord').value,
dateJoined: new Date(),
total: 0,
purchase: {},
deposit: {},
monthlyTotal: 0,
yearlyTotal: 0
};
pageView.setCurrentPage(pageView.getIndex());
pageView.setNav(pageView.getIndexNav());
ko.applyBindings(pageView);
socket.emit('registered', JSONout(reg));
}
});
Server:
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var http = require('http');
var db = mongojs('127.0.0.1:27017/mySpendingDB', ['users']);
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var path = require('path');
app.configure(function () {
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/', function (req, res) {
res.render('mainPage.html', {
title: 'app'
});
});
var user = "";
db.users.find(function (err, docs) {
console.log(docs);
return docs;
});
io.sockets.on('connection', function (socket) {
console.log('socket.io started');
socket.on('login', function (data) {
console.log('login');
var checkUser = db.users.find(data, function (err, docs) {
return docs;
});
console.log(checkUser);
if (checkUser !== null) {
console.log('checked user');
user = checkUser.username;
socket.emit('uploadList', checkUser.total);
} else {
console.log('Log in invalid');
}
});
socket.on('purchaseLog', function (data) {
var usercollection = db.users.find({
username: user
});
usercollection.purchase.save(data);
});
socket.on('depositLog', function (data) {
var usercollection = db.users.find({
username: user
});
usercollection.deposit.save(data);
});
socket.on('goMonthly', function (data) {
var monTot = db.users.find({
username: user
}).monthlyTotal;
socket.emit('wentMonthly', monTot);
});
socket.on('goYearly', function (data) {
var yearTot = db.users.find({
username: user
}).yearlyTotal;
socket.emit('wentYearly', yearTot);
});
socket.on('registered', function (data) {
db.users.save(data);
});
});
server.listen(3000);
Related
I am using the following logic to verify whether client is connected to websocket or not: Client keeps sending pings at an interval to the server. Server has a timeout which triggers an event on completing. As soon as Client pings server, the server timeout resets. This works fine when one client is connected. But the logic breaks on multiple clients. How can I fix this? As soon as 2nd client connects, Server says client 1 has disconnected and doesn't print anything when either of the 2 disconnect.
This is my server logic:
const WebSocket = require("ws");
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const url = require('url');
const PORT = process.env.PORT || 3000;
const wss = new WebSocket.Server({ server: server });
app.get("/", (req, res) => res.send("Temst."));
var tm;
function ping(client) {
tm = setTimeout(function () {
console.log(`[-] ${client} Disconnected`);
wss.emit("customClose", client);
}, 5000);
}
function pong(client) {
clearInterval(tm);
// console.log("[!] Cleared timeout");
ping(client);
}
wss.on("connection", function connection(ws, req) {
var queryData = url.parse(req.url,true).query;
ping(queryData.id);
console.log(`[+] ${req.socket.remoteAddress} Connected`);
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
message = {
type: "alert",
msg: `${queryData.id} has Connected.`,
};
client.send(JSON.stringify(message), { binary: false });
}
});
ws.on("message", function incoming(message) {
if (message == "__ping__") {
console.log(`[!] Ping Receieved from ${req.socket.remoteAddress}`);
pong(queryData.id);
} else {
`[!] Message Receieved from ${req.socket.remoteAddress}`;
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(msg, { binary: false });
}
});
}
});
});
wss.addListener("customClose", function (m) {
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
message = {
type: "alert",
msg: `${m} has Disconnected.`,
};
client.send(JSON.stringify(message), { binary: false });
}
});
});
server.listen(PORT, () => console.log("Listening on port 3000"));
I think I have solved the problem. After looking at the ws package docs, I tried server side pinging instead of client side. It is working for multiple users for now. Will update if any problems occur.
const WebSocket = require("ws");
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const url = require("url");
const PORT = process.env.PORT || 3000;
const wss = new WebSocket.Server({ server: server });
app.get("/", (req, res) => res.send("Temst."));
var myClients = [];
wss.on("connection", function connection(ws, req) {
var queryData = url.parse(req.url, true).query;
myClients.push({
id: queryData.id,
wsoc: ws,
isAlive: true,
});
console.log(`[+] ${req.socket.remoteAddress} Connected`);
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
message = {
type: "alert",
msg: `${queryData.id} has Connected.`,
};
client.send(JSON.stringify(message), { binary: false });
}
});
ws.on("pong", () => {
let x = myClients.find((o) => o.wsoc === ws);
x.isAlive = true;
});
ws.on("message", function incoming(message) {
console.log(`[!] Message Receieved from ${req.socket.remoteAddress}`);
msg = JSON.parse(message);
console.log(queryData);
msg = { ...msg, time: new Date().toISOString() };
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(msg), { binary: false });
}
});
});
});
wss.addListener("customClose", function (m) {
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
message = {
type: "alert",
msg: `${m} has Disconnected.`,
};
client.send(JSON.stringify(message), { binary: false });
}
});
});
const interval = setInterval(function ping() {
myClients.forEach((clnt, index) => {
if (clnt.isAlive === false) {
console.log("[-]", clnt.id, "has Disconnected.");
wss.emit("customClose", clnt.id);
clnt.wsoc.terminate();
myClients.splice(index, 1);
}
clnt.isAlive = false;
clnt.wsoc.ping();
});
}, 5000);
server.listen(PORT, () => console.log("Listening on port 3000"));
I have a file, controller.js in trying to import functionality into app.js.
I keep getting syntax errors:
, expected
statement expected
Simple to fix I though however when I fix one 10 more pop up, So can some one look at my code and see what doing wrong ?
app.js
Promise.all([controller.firstFunction(), controller.secondFunction()]) .then(controller.thirdFunction);
controller.js
module.exports = {
var express = require('express');
// var rp = require('request-promise');
var app = express();
// var request = require('request');
var nodePardot = require('node-pardot');
// Credential's for pardot API
var password = ';lu.88';
var userkey = 'kol;';
var emailAdmin = 'j.j#jj.co.uk';
//
// // Start the server
// app.listen(port);
// app.use(bodyParser.json()); // support json encoded bodies
// app.use(bodyParser.urlencoded({extended: true})); // support encoded bodies
// console.log('Test server started! At http://localhost:' + port); // Confirms server start
//
// app.use('/', router);
var firstFunction = function () {
return new Promise(function (resolve) {
setTimeout(function () {
app.post('/back-end/test', function (req, res) {
console.log(req.body);
var login = req.body.LoginEmail;
res.send(login);
resolve({
data_login_email: login
});
});
console.error("First done");
}, 2000);
});
};
var secondFunction = function () {
return new Promise(function (resolve) {
setTimeout(function () {
nodePardot.PardotAPI({
userKey: userkey,
email: emailAdmin,
password: password,
DEBUG: false
}, function (err, client) {
if (err) {
// Authentication failed
console.error("Authentication Failed", err);
} else {
// Authentication successful
var api_key = client.apiKey;
console.log("Authentication successful !", api_key);
resolve({data_api: api_key});
}
});
console.error("Second done");
}, 2000);
});
};
function thirdFunction(result) {
return new Promise(function () {
setTimeout(function () {
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
};
// Configure the request
var api = result[1].data_api;
var login_email = result[0].data_login_email;
var options = {
url: 'https://pi.pardot.com/api/prospect/version/4/do/read',
method: 'POST',
headers: headers,
form: {
'email': login_email,
'user_key': userkey,
'api_key': api
},
json: true // Automatically stringifies the body to JSON
};
// Start the request
rp(options)
.then(function (parsedBody) {
console.error(login_email, "Is a user, login pass!");
})
.catch(function (err) {
console.error("fail no such user");
// res.status(400).send()
});
console.error("Third done");
}, 3000);
}
);
}
};
This is because you wrapped your code inside an object, {} tags.
You have a couple of options, my suggestion is to use Prototypes like so
var express = require('express');
// var rp = require('request-promise');
var app = express();
// var request = require('request');
var nodePardot = require('node-pardot');
// Credential's for pardot API
var password = ';lu.88';
var userkey = 'kol;';
var emailAdmin = 'j.j#jj.co.uk';
//
// // Start the server
// app.listen(port);
// app.use(bodyParser.json()); // support json encoded bodies
// app.use(bodyParser.urlencoded({extended: true})); // support encoded bodies
// console.log('Test server started! At http://localhost:' + port); // Confirms server start
//
// app.use('/', router);
function Functions(){};
Functions.prototype.firstFunction = function () {
return new Promise(function (resolve) {
setTimeout(function () {
app.post('/back-end/test', function (req, res) {
console.log(req.body);
var login = req.body.LoginEmail;
res.send(login);
resolve({
data_login_email: login
});
});
console.error("First done");
}, 2000);
});
};
Functions.prototype.secondFunction = function () {
return new Promise(function (resolve) {
setTimeout(function () {
nodePardot.PardotAPI({
userKey: userkey,
email: emailAdmin,
password: password,
DEBUG: false
}, function (err, client) {
if (err) {
// Authentication failed
console.error("Authentication Failed", err);
} else {
// Authentication successful
var api_key = client.apiKey;
console.log("Authentication successful !", api_key);
resolve({data_api: api_key});
}
});
console.error("Second done");
}, 2000);
});
};
Functions.prototype.thirdFunction(result) {
return new Promise(function () {
setTimeout(function () {
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
};
// Configure the request
var api = result[1].data_api;
var login_email = result[0].data_login_email;
var options = {
url: 'https://pi.pardot.com/api/prospect/version/4/do/read',
method: 'POST',
headers: headers,
form: {
'email': login_email,
'user_key': userkey,
'api_key': api
},
json: true // Automatically stringifies the body to JSON
};
// Start the request
rp(options)
.then(function (parsedBody) {
console.error(login_email, "Is a user, login pass!");
})
.catch(function (err) {
console.error("fail no such user");
// res.status(400).send()
});
console.error("Third done");
}, 3000);
}
);
}
module.exports = Functions;
Then you would create a instance of the class within the file you require it (in this case app.js)
var myFunctions = new Functions();
From there you can access your methods using:
myFunctions.firstFunction();
If you however wanted to go on about the way you have done so already, you should use object structure like so
module.exports = {
firstFunction : function()
{
//Function Body
},
secondFunction : function()
{
//Function Body
}
}
Issue with you code is :
you were using var inside module.export and that means you are declaring var inside export that is not valid,
module.export should be in json format.
Try this code :
var express = require('express');
// var rp = require('request-promise');
var app = express();
// var request = require('request');
var nodePardot = require('node-pardot');
// Credential's for pardot API
var password = ';lu.88';
var userkey = 'kol;';
var emailAdmin = 'j.j#jj.co.uk';
//
// // Start the server
// app.listen(port);
// app.use(bodyParser.json()); // support json encoded bodies
// app.use(bodyParser.urlencoded({extended: true})); // support encoded bodies
// console.log('Test server started! At http://localhost:' + port); // Confirms server start
//
// app.use('/', router);
module.exports = {
firstFunction : function () {
return new Promise(function (resolve) {
setTimeout(function () {
app.post('/back-end/test', function (req, res) {
console.log(req.body);
var login = req.body.LoginEmail;
res.send(login);
resolve({
data_login_email: login
});
});
console.error("First done");
}, 2000);
});
},
secondFunction : function () {
return new Promise(function (resolve) {
setTimeout(function () {
nodePardot.PardotAPI({
userKey: userkey,
email: emailAdmin,
password: password,
DEBUG: false
}, function (err, client) {
if (err) {
// Authentication failed
console.error("Authentication Failed", err);
} else {
// Authentication successful
var api_key = client.apiKey;
console.log("Authentication successful !", api_key);
resolve({data_api: api_key});
}
});
console.error("Second done");
}, 2000);
});
},
thirdFunction : function(result) {
return new Promise(function () {
setTimeout(function () {
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
};
// Configure the request
var api = result[1].data_api;
var login_email = result[0].data_login_email;
var options = {
url: 'https://pi.pardot.com/api/prospect/version/4/do/read',
method: 'POST',
headers: headers,
form: {
'email': login_email,
'user_key': userkey,
'api_key': api
},
json: true // Automatically stringifies the body to JSON
};
// Start the request
rp(options)
.then(function (parsedBody) {
console.error(login_email, "Is a user, login pass!");
})
.catch(function (err) {
console.error("fail no such user");
// res.status(400).send()
});
console.error("Third done");
}, 3000);
}
);
}
};
You need to use object notation inside of an object ( module.exports):
var express = require('express');
// var rp = require('request-promise');
var app = express();
// var request = require('request');
var nodePardot = require('node-pardot');
// Credential's for pardot API
var password = ';lu.88';
var userkey = 'kol;';
var emailAdmin = 'j.j#jj.co.uk';
module.exports = {
firstFunction() {
return new Promise(function(){
...
});
},
secondFunction(){},
thirdFunction(){}
};
and exporting dependencies and passwords is not really useful...
I am getting this error:
Cannot POST/.
Below is the code I'm trying to execute.
Server.js
var express = require('express');
var bodyParser = require('body-parser');
var _ = require('underscore');
var db = require('./db.js');
var bcryptjs = require('bcryptjs');
var middleware = require('./middleware.js')(db);
var http = require('http').Server(app);
var app = express();
var PORT = process.env.PORT || 3000;
var todos = [];
var todoNextId = 1;
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.get('/', function(req, res) {
res.send('Todo API Root');
});
app.get('/todos', middleware.requireAuthentication, function(req, res) {
var query = req.query;
var where = {
userId: req.user.get('id')
};
if (query.hasOwnProperty('completed') && query.completed === 'true') {
where.completed = true;
} else if (query.hasOwnProperty('completed') && query.completed === 'false') {
where.completed = false;
}
if (query.hasOwnProperty('q') && query.q.length > 0) {
where.description = {
$like: '%' + query.q + '%'
};
}
db.todo.findAll({
where: where
}).then(function(todos) {
res.json(todos);
}, function(e) {
res.status(500).send();
});
});
app.get('/todos/:id', middleware.requireAuthentication, function(req, res) {
var todoId = parseInt(req.params.id, 10);
db.todo.findOne({
where: {
id: todoId,
userId: req.user.get('id')
}
}).then(function(todo) {
if (!!todo) {
res.json(todo.toJSON());
} else {
res.status(404).send();
}
}, function(e) {
res.status(500).send();
});
});
app.post('/todos', middleware.requireAuthentication, function(req, res) {
var body = _.pick(req.body, 'description', 'completed');
db.todo.create(body).then(function(todo) {
req.user.addTodo(todo).then(function () {
return todo.reload();
}).then(function (todo) {
res.json(todo.toJSON());
});
}, function(e) {
res.status(400).json(e);
});
});
app.delete('/todos/:id', middleware.requireAuthentication, function(req, res) {
var todoId = parseInt(req.params.id, 10);
db.todo.destroy({
where: {
id: todoId,
userId: req.user.get('id')
}
}).then(function(rowsDeleted) {
if (rowsDeleted === 0) {
res.send(404).json({
error: 'No todo with id'
});
} else {
res.status(204).send();
}
}, function() {
res.status(500).send();
});
});
app.put('/todos/:id', middleware.requireAuthentication, function(req, res) {
var todoId = parseInt(req.params.id, 10);
var body = _.pick(req.body, 'description', 'completed');
var attributes = {};
if (body.hasOwnProperty('completed')) {
attributes.completed = body.completed;
}
if (body.hasOwnProperty('description')) {
attributes.description = body.description;
}
db.todo.findOne({
where: {
id: todoId,
userId: req.user.get('id')
}
}).then(function(todo) {
if (todo) {
todo.update(attributes).then(function(todo) {
res.json(todo.toJSON());
}, function(e) {
res.status(400).json(e);
});
} else {
res.status(404).send();
}
}, function() {
res.status(500).send();
});
});
app.post('/users', function(req, res) {
var body = _.pick(req.body, 'email', 'password');
db.user.create(body).then(function(user) {
res.json(user.toPublicJSON());
}, function(e) {
res.status(400).json(e);
});
});
app.post('/users/login', function (req, res) {
var body = _.pick(req.body, 'email', 'password');
var userInstance;
db.user.authenticate(body).then(function (user) {
var token = user.generateToken('authentication');
userInstance = user;
return db.token.create({
token: token
});
}).then(function (tokenInstance) {
res.header('Auth',
tokenInstance.get('token')).json(userInstance.toPublicJSON());
}).catch(function () {
res.status(401).send();
});
});
app.delete('/users/login', middleware.requireAuthentication,
function (req, res) {
req.token.destroy().then(function () {
res.status(204).send();
}).catch(function () {
res.status(500).send();
});
});
db.sequelize.sync({force: true}).then(function() {
app.listen(PORT, function() {
console.log('Express listening on port ' + PORT + '!');
});
});
This is my app.js file
app.post('/users', function(req, res) {
var body = _.pick(req.body, 'email', 'password');
db.user.create(body).then(function(user) {
res.json(user.toPublicJSON());
}, function(e) {
res.status(400).json(e);
});
});
I've been trying this but not getting through.Not sure whether the html file I have is correct. Want to create an html file to post from, but mine is refusing to respond.
You cannot POST to / because you haven't defined a route handler for POST requests to / (you only have one for GET to /).
I am trying to access a Magento SOAP API (v 1.9.2.4) using npm magento. But data is always null:
var express = require('express');
var app = express();
var MagentoAPI = require('magento');
var magento = new MagentoAPI({
host: 'localhost',
port: 8080,
path: '/magento/api/xmlrpc/',
login: 'mothership',
pass: 'bvZ0k0B02pTjujN'
});
app.get('/', function (req, res) {
res.send('Customers: ');
});
var magentoCallback = function(data) {
console.log('Got data: ' + data);
console.log(data);
};
magento.login(function(err, sessId) {
if (err) {
console.log("Error accessing Magento");
console.log(err);
console.log("Session ID: " + sessId);
return;
}
console.log("Connected to Magento");
magento.core.info(magentoCallback);
});
app.listen(3000, function () {
console.log('Racing on port 3000');
});
today, i was the same problem and after two hours i found the resolution. You need change the magentoCallback function to :
var magentoCallback = function(err, response) {
if (err) {
return console.log(err);
}
console.log("Result: ");
console.log(response)
};
I'm new to Node.js I followed tutorial from the internet for REST API with Node.js and MySQL. I can't get it to work after MySQL closes the connection or timeout occurs. Can you tell me how to modify my code to get it work:
Server.js
var express = require("express");
var mysql = require("mysql");
var bodyParser = require("body-parser");
var rest = require("./REST.js");
var app = express();
function REST(){
var self = this;
self.connectMysql();
};
REST.prototype.connectMysql = function() {
var self = this;
var pool = mysql.createPool({
connectionLimit : 50,
host : 'localhost',
user : 'root',
password : '',
database : 'quiz',
debug : false,
multipleStatements: true
});
pool.getConnection(function(err,connection){
if(err) {
self.stop(err);
} else {
self.configureExpress(connection);
}
});
}
REST.prototype.configureExpress = function(connection) {
var self = this;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var router = express.Router();
app.use('/', router);
var rest_router = new rest(router,connection);
self.startServer();
}
REST.prototype.startServer = function() {
app.listen(3000,function(){
console.log("All right ! I am alive at Port 3000.");
});
}
REST.prototype.stop = function(err) {
console.log("ISSUE WITH MYSQL n" + err);
process.exit(1);
}
new REST();
REST.js
var mysql = require("mysql");
function REST_ROUTER(router,connection) {
var self = this;
self.handleRoutes(router,connection);
}
REST_ROUTER.prototype.handleRoutes= function(router,connection) {
router.get("/",function(req,res){
res.json({"Message" : "Hello World !"});
});
router.get("/quiz/cars",function(req,res){
var options = {sql: 'SELECT quiz.quiz_id, quiz_image, quiz_type, choice_id, choice, is_right_choice FROM quiz JOIN quiz_choices ON quiz.quiz_id = quiz_choices.quiz_id WHERE quiz_type="cars";', nestTables: false};
connection.query(options,function(err,rows){
if(err) {
res.json({"Error" : true, "Message" : "Error executing MySQL query"});
} else {
res.json(rows);
}
});
});
}
module.exports = REST_ROUTER;
I have the same issue a and think this may be the solution. I made the following changes to my code:
Pass the connection pool rather than the connection to self.configureExpress() like so...
REST.prototype.connectMysql = function() {
var self = this;
var pool = mysql.createPool(db_config);
self.configureExpress(pool);
};
and
REST.prototype.configureExpress = function(pool) {
....
var rest_router = new rest(router,pool,md5);
....
}
REST.js
var mysql = require("mysql");
function REST_ROUTER(router,pool) {
var self = this;
self.handleRoutes(router,pool);
}
REST_ROUTER.prototype.handleRoutes= function(router,pool) {
router.get("/",function(req,res){
res.json({"Message" : "Hello World !"});
});
router.get("/quiz/cars",function(req,res){
var options = {sql: 'SELECT quiz.quiz_id, quiz_image, quiz_type, choice_id, choice, is_right_choice FROM quiz JOIN quiz_choices ON quiz.quiz_id = quiz_choices.quiz_id WHERE quiz_type="cars";', nestTables: false};
pool.getConnection(function(err, connection) {
connection.query(options,function(err,rows){
connection.release();
if(err) {
res.json({"Error" : true, "Message" : "Error executing MySQL query"});
} else {
res.json(rows);
}
});
});
});
}
module.exports = REST_ROUTER;
Don't forget to call connection.release(); after you've finished using the connection so that it can be added back to the connection pool.