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.
Related
When I pass objectid of 1 hospital from Postman to this program it returns only empty array. But there is one data matching that objectid. Can you help me solve this? When I try to debug the program in console, I saw the array is empty.
doctor.js:
var express = require('express');
var router = express.Router();
var app=express()
var bodyParser = require("body-parser");
var validator = require('validator');
var mongo= require('./mongoconnect')
var authentication=require('./check_authentication')
var validate = require('./validation')
var ObjectId=require('mongodb').ObjectId
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
router.post('/',function(req,res)
{
if(validate.name(req.body.name) && validate.length(req.body.name) && validate.empty(req.body.name))
{
if(validate.empty(req.body.hospital_id))
{
mongo.find("hospital","_id",ObjectId(req.body.hospital_id),function(result1)
{
if(result1.length==1)
{
res.send("succcess")
}
})
}
}
})
module.exports = router;
And collection of MongoDB is:
hospital:
{
"_id" : ObjectId("5aa92df0ec6b3cc78ff88afd"),
"name" : "apollo_hospitals"
}
{
"_id" : ObjectId("5aa92df9ec6b3cc78ff88afe"),
"name" : "fortis"
}
mongoconnect.js:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var dbo=null;
exports.connection=function()
{
if(dbo!=null) return
MongoClient.connect(url, function(err, db)
{
if (err) throw err;
dbo = db.db("hospital_api");
});
}
var get = function (){
return dbo;
}
exports.find=function(collections,key,value,callback)
{
get().collection(collections).find({key:value}).toArray(function(err,result)
{
// console.log(collections)
// console.log(key)
// console.log(value)
if(err) throw err;
console.log(result)
callback(result)
})
}
Here, myself i got the solution.
We have to declare ObjectID with New keyword..
Var some_variable = New ObjectID(_id)
After that we can use that id anywhere using that some_variable
i'm trying to create post method for rest api using node js, but it says cannot post /api/v1/user in postman and insomnia, but in the console there's no error, can anyone help me?
Here are my code
server.js
// require dependencies
var app = require('express')();
var http = require('http').Server(app);
var mysql = require('mysql');
var bodyParser = require("body-parser");
// end require
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// load controller
var welcome = require('./controllers/welcome.js');
var users = require('./controllers/user_controller.js');
// end of load controller
// This is the API Route
// Base Route
app.get('/api/v1', welcome.getApi);
// User Route
app.post('api/v1/user', users.post);
http.listen(8080,function(){
console.log("Connected & Listen to port 8080");
});
user_model.js
var mysql = require('mysql');
const uuid = require('uuid/v4');
var connection = require('../config/conn.js');
var knex = require('knex')(connection);
// const salt = "QxLUF1bgIAdeQX";
// const crypto = require('crypto');
var moment = require('moment');
var table = "t_user";
module.exports = {
post: function (req, callback) {
var Id = uuid();
var usrnm = req.body.usrnm;
var pass = req.body.pass;
var mail = req.body.mail;
var name = req.body.name;
var gndr = req.body.gndr;
var addrss = req.body.addrss;
var rl = req.body.rl;
var crt = moment().format('MMMM Do YYYY, h:mm:ss a');
var mdf = moment().format('MMMM Do YYYY, h:mm:ss a');
var dlt = "";
knex(table)
.insert({
id: Id,
username: usrnm,
password: pass,
email: mail,
realname: name,
gender: gndr,
address: addrss,
role: rl,
created_at: crt,
modified_at: mdf,
deleted_at: dlt
})
.then(function (rows){
callback(null, rows);
})
.catch(function (err){
callback(err);
});
console.log("test");
}
}
user_controller.js
var model = require('../models/user_model.js');
var data = {
"count" : 0,
"status" : "",
"detail" : ""
};
module.exports = {
post: function (req,res) {
model.post(req, function (error,result){
if(error){
data["status"] = "error";
data["detail"] = error;
}
else{
data["status"] = "success";
data["detail"] = result;
}
res.json(data);
})
}
}
You probably missed slash here:
app.post('api/v1/user', users.post); // must be '/api/v1/user'
Might want to look at the Security Best Practices for Express
https://expressjs.com/en/advanced/best-practice-security.html
I'm trying to do a query on my SQL Server, the connection works fine and rises an error when I change the password.
The "error" is on request.query(sql, callback), this function is not returning a callback
The connection code:
var sql = require('mssql');
var config = {
user: 'user',
password: 'password',
server: 'ip',
database: 'database',
connectionTimeout: '5000',
requestTimeout: '5000',
options: {encrypt: true}
};
var pool = function(){
var conn = new sql.Connection(config, function(err){
var request = new sql.Request(conn);
//console.dir(request);
return request;
});
return conn;
}
module.exports = function(){
return pool;
}
DAO:
function CampanhaDAO(connection){
this._connection = connection;
//console.log(this._connection)
}
CampanhaDAO.prototype.getCampanhas = function(){
var sql = "SELECT * FROM notificacao_campanha";
this._connection.query(sql, function(err, recordset){
console.log(recordset);
});
};
module.exports = function(){
return CampanhaDAO;
};
Controller:
module.exports.campanhas = function(app, req, res){
var connection = app.config.dbConnection();
var campanhaDAO = new app.dao.CampanhaDAO(connection);
campanhaDAO.getCampanhas(function(error, result){
console.log("gerou");
res.send(result);
});
}
Can anyone help me?
I am writing a url shortener service in Node JS using mongo to connect to mLab.
Right now the user can send a request to the service with a url to shorten, and it returns a shortened url. However, if the user then sends the shortened url as a request, the redirect does not happen. Rather, the service goes into a loop.
1) How do I see what exactly is getting grabbed from the db? (Knowing how to do this would help out in trouble-shooting)
2) And what may be the cause of the looping issue?
var express = require('express')
var app = express()
var path = require('path');
var port = process.env.PORT || 8080;
var crypto = require("crypto");
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({ // this schema is used for writing to the db
url : String,
key : String
});
var urlcntrctr = new Schema( // this schema is used for reading from the db
{ key: String, url : String, _id: String },
{ collection: 'urlcntrctr'}
);
const SchemaName = mongoose.model('SchemaName', urlcntrctr); // for reading from the db
app.get('/', (req, res, next) => res.sendFile(path.join(__dirname, '/index.html')) ) ;
app.set('port', (process.env.PORT || 5000));
app.get('/new/:url(*)', function(req, res) {
var shortenme = req.params[0];
var showme = req.params[0];
console.log("User's request: " +shortenme);
var amItrue = validateURL(shortenme);
if (amItrue){
connectmongoviamongoose();
var shortenmeObj = yncryptyyn(shortenme);
shortenme = shortenmeObj.key;
writeToDb(shortenmeObj); b
closetheconnection();
var contractedurl = 'http://firstappever-olddognewtrix123.c9users.io/' + shortenme;
var responseObject = ({"Original url: ": showme, "Contracted url: ": shortenme });
res.send(responseObject);
}
else{console.log("You need to enter a url, beginning with 'http' or 'https' and ending in '.com' or '.org' or whatever!");};
})
app.get('/:tag(*)', function(req, res) {
var targetnumber = req.params.tag;
sendforRedirect(req, res);
sendforRedirect(req, res);
})
function sendforRedirect(req, res){
var target = req.params.tag;
console.log("The value of target is " + target)
; var options = { server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 1, connectTimeoutMS : 30000 } } };
var mongodbUri = 'mongodb://<dbusername>:<dbuserpassword>#ds159988.mlab.com:59988/urlcntrctr';
mongoose.connect(mongodbUri, options);
mongoose.Promise = global.Promise;
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function() {
console.log("OK, you are connected for the redirect. ")
var query = {
key: {
$eq: target
}
}
SchemaName.find(query, function (err, doc) {
if(err){
console.log(err);
conn.close();
};
if(doc){
res.redirect(doc.url); // rather than redirecting, it is looping *****************
conn.close();
} else {
res.send("Sorry, we don't recognize that url");
conn.close();
}
});
});
}
function writeToDb(dataObject){
mongoose.model('Document', UserSchema);
var urlFromUser = mongoose.model('Document');
var urlfromuser = new urlFromUser();
urlfromuser.url = dataObject.url;
urlfromuser.key = dataObject.key;
urlfromuser.save();
};
function validateURL(textval) { //copied from http://stackoverflow.com/questions/1303872/trying-to-validate-url-using-javascript
var urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*#)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/;
return urlregex.test(textval);
}
function connectmongoviamongoose(){
var mongoose = require('mongoose');
var options = { server: { socketOptions: { keepAlive: 300000, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 300000, connectTimeoutMS : 30000 } } };
var mongodbUri = 'mongodb://<dbusername>:<dbuserpassword>#ds159988.mlab.com:59988/urlcntrctr';
mongoose.createConnection(mongodbUri, options);
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function() {
console.log("OK, you are connected. ")
});
}
function closetheconnection(){
var mongoose = require('mongoose');
mongoose.connection.close();
}
function yncryptyyn(incryptme){
var ulimit = 6;
var key = crypto.createHash('md5').update(incryptme).digest("base64");
key = key.slice(0,ulimit);
var obj = {
url: incryptme,
key: key
};
return obj;
}
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
Better than console.log statements, you can use the package node-inspector to actually set breakpointsnin your code via chrome devtools and step through the code Much more robust process.
I would note that it is not clear to me what kind of urls you are shortening (internal to your site or external), but at present it looks like you're calling the redirect function twice, which should cause an error unto itself, and second if you are redirecting to internal urls your routes are probably going to match a lot that you don't want them to.
Finally, your code is kind of a jumble right now, which will make debugging harder no matter what you do. Try and break it out into different files based on what they do and test bits independently as much as possible.
For question 1: just put in a console.log, for example like this:
if(doc){
console.log(doc);
res.redirect(doc.url);
....
Even better put the whole functionality of the look up of the url into an own function, so you can check the working of the lookup and the working of the redirect independently.
I am running this script with node child_process.fork api.
That is my express application script, from where I start my application:
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path');
var app = express();
//database connection
var connection = require('express-myconnection');
var mysql = require('mysql');
//all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
//development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.use(
connection(mysql,{
host: 'localhost',
user: 'root',
password : '',
port : 3306, //port mysql
database:'test-db'
},'pool')
);
//routes
//app.get('/', routes.index);
app.get('/', routes.list);
app.use(app.router);
//run script
var cp = require('child_process');
var child = cp.fork('dataGrabber/pusherMysql');
child.on('message', function(m) {
// Receive results from child process
console.log('received: ' + m);
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port') + ' http://localhost:' + app.get('port'));
});
That`s the part where I run my script:
//run script
var cp = require('child_process');
var child = cp.fork('dataGrabber/pusherAPI');
child.on('message', function(m) {
// Receive results from child process
console.log('received: ' + m);
});
As you can see I load my script and want to receive a message from the child.
That is my pusherAPI.js script:
var mysql = require('mysql');
var Pusher = require('pusher-client');
/**
* connect with mysql db
*/
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
database : 'test-db',
port : '3306',
password : ''
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
//connect with the server
var API_KEY = 'cb65d0a7a72cd94adf1f';
var pusher = new Pusher(API_KEY, {
encrypted: true
});
var channel = pusher.subscribe("ticker.160");
channel.bind("message", function(data) {
console.log(data);
this.data = data;
/**
* save data to db
*/
var trade = {
timestamp : data.trade.timestamp,
price : data.trade.topbuy.price,
};
var query = connection.query('INSERT INTO trades SET ?', trade, function(err, result) {
if (err) {
connection.rollback(function() {
throw err;
});
}
//push message back to the app.js
process.on('message', function(m) {
// Pass results back to parent process
m = "insert happened";
process.send(m);
});
connection.commit(function(err) {
if (err) {
connection.rollback(function() {
throw err;
});
}
});
});
console.log(query.sql);
});
I want to send a message back to my app.js, whenever an insertion happened to my sql db
My script starts and runs my queries. However, process.send(m); does not send anything back.
Any recommendations what I am doing wrong?
I appreciate your answer!
Update
When changing my pusherAPI.js to, I get nothing back in the console.
var channel = pusher.subscribe("ticker.160");
process.on('insert_message', function(m) {
channel.bind("message", function(data) {
console.log(data);
this.data = data;
/**
* save data to db
*/
var trade = {
timestamp : data.trade.timestamp,
price : data.trade.topbuy.price,
};
var query = connection.query('INSERT INTO trades SET ?', trade, function(err, result) {
if (err) {
connection.rollback(function() {
throw err;
});
}
//push message back to the app.js
// Pass results back to parent process
m = "insert happened";
process.send(m);
connection.commit(function(err) {
if (err) {
connection.rollback(function() {
throw err;
});
}
});
});
console.log(query.sql);
});
});
In my app.js I changed my code like that:
//run script
var cp = require('child_process');
var child = cp.fork('dataGrabber/pusherAPI');
child.on('insert_message', function(m) {
// Receive results from child process
console.log('received: ' + m);
});
Move your process.send(m); outside of the message event handler. Otherwise you're adding a new message event handler for every query and those event handlers only fire when the parent process sends it a message. Example:
var channel = pusher.subscribe("ticker.160");
channel.bind("message", function(data) {
this.data = data;
/**
* save data to db
*/
var trade = {
timestamp : data.trade.timestamp,
price : data.trade.topbuy.price,
};
var query = connection.query('INSERT INTO trades SET ?',
trade,
function(err, result) {
if (err) {
connection.rollback(function() {
throw err;
});
return;
}
//push message back to the app.js
m = "insert happened";
process.send(m);
connection.commit(function(err) {
if (err) {
connection.rollback(function() {
throw err;
});
}
});
});
});