Node js - Make pretty url ejs - mysql

I am new to nodejs and I was wondering if there is possibility to make pretty url in nodejs. I am trying to implement custom pagination on a table. I want the pagination page url should be like
http://localhost:3001/users/page/2
Instead of
http://localhost:3001/users?page=2
Here is my route code
const express = require('express');
const mysql = require('mysql');
const router = express.Router();
const authenticate = require('./middleware');
const connection = require('./lib/db');
// get all users listing
router.get('/users/:page', authenticate.login, function (req, res) {
console.log('request',req.params.page);
var cur = typeof req.params.page != "undefined" ? req.params.page : 1;
var limit = cur - 1;
limit = limit * 10;
connection.query('SELECT count(*) as total FROM lc_users', function(error, rws, flds) {
if(error) throw error
connection.query(mysql.format('SELECT * FROM lc_users ORDER BY uid DESC LIMIT ?,10',[limit]), function(err, rows, fields) {
if(err) throw err
res.render('Users/users',{
title: 'Users',
session: res.locals.session,
usersList: rows,
total: rws[0].total,
current: cur
});
});
});
});
Now when I try to open http://localhost:3001/users url I get error of no route found. I know the issue is with addition /page/ added in the url and that's why its not recognizing the correct route.
Can anyone suggest me what I am doing wrong?
Many Thank!

Related

NodeJS to Postman Result

Good Day how can i compute a public function to route and check it on Postman? here is my codes
router.post('/post_regular_hours/:employee_id/',function(request,response,next){
var id = request.params.employee_id;
var time_in = request.params.time_in;
var time_out = request.params.time_out;
// const timein = request.params.time_in;
// const timeout = request.params.time_out;
knexDb.select('*')
.from('employee_attendance')
.where('employee_id',id)
.then(function(result){
res.send(compute_normal_hours(response,result,diff))
})
});
function compute_normal_hours(res,result,diff){
let time_in = moment(time_in);
let time_out = moment(time_out);
let diff = time_out.diff(time_in, 'hours');
return diff;
}
I want the Diff to get posted on Postman as a result
Here is the App.js of my codes. How can i call the data from mysql query to the function and return the computed data on router post
or can you guys give the right terminologies for it.
var express = require('express');
var mysql= require('mysql');
var employee = require('./routes/employee');
var time_record = require('./routes/time_record');
var admin_employee = require('./routes/admin_employee');
var tar = require('./routes/tar');
var Joi = require('joi');
var app = express();
app.get('/hello',function(req,res){
var name = "World";
var schema = {
name: Joi.string().alphanum().min(3).max(30).required()
};
var result = Joi.validate({ name : req.query.name }, schema);
if(result.error === null)
{
if(req.query.name && req.query.name != '')
{
name = req.query.name;
}
res.json({
"message" : "Hello "+name + "!"
});
}
else
{
res.json({
"message" : "Error"
});
}
});
//Database connection
app.use(function(req, res, next){
global.connection = mysql.createConnection({
host : 'locahost',
user : 'dbm_project',
password : 'dbm1234',
database : 'dbm_db'
});
connection.connect();
next();
});
app.use('/', employee);
app.use('/employee', time_record);
app.use('/admin', admin_employee);
app.use('/tar', tar);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.listen(8000,function(){
console.log("App started on port 8000!");
});
module.exports = app;
Here is the App.js of my codes. How can i call the data from mysql query to the function and return the computed data on router po
There are a few problems with your code.
Please see explanations in the respective code chunks.
router.post('/post_regular_hours/:employee_id/',function(request,response,next){
// If you're receiving a post request
// you'll probably want to check the body for these parameters.
let id = request.params.employee_id; // make sure the param names are matching with what you post.
// This one is special because you are passing it through the url directly
let time_in = request.body.time_in;
let time_out = request.body.time_out;
knexDb.select('*')
.from('employee_attendance')
.where('employee_id',id)
.then(function(result){
// you are not sending time_in and time_out here - but difference. but difference is not calculated.
// changed the function signature a bit - you weren't using the result at all? leaving this callback here because I'm sure you want to map the used time to some user?
return response.send(compute_normal_hours(time_in, time_out))
});
});
// this function was (and still might be) incorrect.
// You were passing res and result which neither of them you were using.
// You also had time_in and time_out which were going to be undefined in the function scope. Now that we are passing them in it should be ok. Updated it so you don't have the params you don't need.
function compute_normal_hours(time_in, time_out){
// What was diff - if it's the time difference name things correctly
// You had a diff parameter passed in (which you didn't compute), a diff function called below and another variable declaration called diff.
// you were not passing time_in or time_out parameters.
// you have moment here - are you using a library?
let time_in = moment(time_in);
let time_out = moment(time_out);
let diff = time_out.diff(time_in, 'hours');
return `Computed result is: ${diff}`;
}
Important Edit
Please search for all occurences of res.render (response.render) and replace them with something like res.send - res.render is looking for the template engine

Call sql query synchrously

Currently working on node rest api project where I want to fetch data for a list of data. for example : I have a list of post_id([1,2,3....]) for a particular tag(mobile) and for each post_id I want to retrieve post title and description from mysql database. But calling sql query is synchrounous.
How to control flow for each post id result to combine in one.
my db calling code is here :
var express = require('express');
var app = express();
var bodyParser = require('body-parser'); // call body-parser
var addData = require('./dbhandler/addData'); // call database handler to insertdata
var getData = require('./dbhandler/getData');
//route function to get feeds by tags
router.route('/postfeedsbytags/:tag')
// get all new article feeds filtered by tag
.get(function(req,res){
var success;
console.log(req.params.tag)
var json_results = [];
getData.getPostFeedsByTag(req.params.tag,function(error, results, fields){
if (!error){
for (var i = 0; i < results.length; i++) {
getData.getPostFeedsByPostId(results[0]['post_id'],function(error, results, fields){
if (!error){
success = 1;
json_results.push(results[0]);
res.json({"success" : success, "datasets" : json_results});
} else{
success = 0;
console.log('Error while performing Query.'+error);
res.json({"success" : success});
}
});
}
// res.json({"success" : success, "datasets" : results});
} else{
success = 0;
console.log('Error while performing Query.'+error);
res.json({"success" : success});
}
});
});
I think you can use the IN operator in the query to get all the posts in a single query and then iterate over it.
If you don't want to use IN operator then use async library for flow control. You can use the async.map function from it.

Node/Express + MySQL: Inserts not displaying instantly

I have a form called #add_blog_post with the action "/mysql_test/add_blog_post" and method of "POST"
Jade markup:
form#add_blog_post(action="/mysql_test/add_blog_post" method="POST")
This form executes the following code in my app.js:
app.post('/mysql_test/add_blog_post', function(req, res) {
var author = req.body.author;
var date = req.body.date;
var title = req.body.title;
var body = req.body.body;
var blog_insert_query = "insert into 332project.blog(author,date,title,body) values(";
blog_insert_query += ("'"+author+"'"+","); blog_insert_query += ("'"+date+"'"+","); blog_insert_query += ("'"+title+"'"+","); blog_insert_query += ("'"+body+"'"+")");
var connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS
});
connection.connect(function(err) { /*error?*/ });
var result;
var query = connection.query(blog_insert_query, function(err, result) {
res.redirect('/mysql_test');
});
});
The blog post insert works just fine but the website takes a while for the insert to be displayed from the select statement on /mysql_test.
Here is my route:
var express = require('express');
var router = express.Router();
var db_calls = require('../db.js');
var connection = db_calls.connect();
connection.connect(function(err) { /*error?*/ });
var result;
var query = connection.query("select * from 332project.blog order by id desc", function(err, rows, fields) {
connection.end();
if (!err) {
result = rows;
}
});
router.get('/', function(req, res, next) {
res.render('mysql_test', {
result: result
});
});
module.exports = router;
What gives? It almost seems like a caching issue. I'd really like for my create/update operations to be instantly visible in my application.
Source code: https://github.com/harwoodjp/learning-express
Your problem is probably that you're not calling connection.end() per the docs.

Whats wrong with this express code?

Hello i am trying to check two mysql values and if its matching anything in the database it needs to generate a token but it does not seem to work :(
Everytime i run this code i get a connection time out:
var express = require('express');
var router = express.Router();
var mysql = require("mysql");
var randomstring = require("randomstring");
/* GET users listing. */
router.get('/', function(req, res, next) {
// First you need to create a connection to the db
var connection = mysql.createConnection({
host: "localhost",
user: "segfault",
password: "wnk9ctte2endcKzBKtre7auE",
database: "segfault"
});
connection.connect();
var input_user = req.body.username;
var input_pass = req.body.password;
var token = randomstring.generate(12);
connection.query('SELECT username FROM segfault.users AS username', function(err, rows, fields) {
if (err) throw err;
for(var i in rows){
username = rows[i].username;
if(input_user == username){
connection.query('SELECT password FROM segfault.users AS password', function(err, rows, fields) {
if(rows[i].password == input_pass){
res.send("OK: "+ token);
console.log("OK:" + token)
}
});
}
}
});
connection.end();
});
module.exports = router;
tell me please what i am dooing wrong!
You close the connection to the database without waiting for the result of the query.
Move connection.end(); inside callback after the res.send.

Read, Display and Insert into another Table

I am new to NodeJS programming,
Have created a script which reads from Database table nodetest having 50K records and displays in the browser and then writes to another table called 'nodetestcopy'
var express = require('express');
var app = express();
var connection = require('express-myconnection');
var mysql = require('mysql');
var rows={};
var copyOfrows={
'id':null,
'f_name':null,
'l_name':null,
'title':null
};
var date1 = (new Date()).getTime();
app.use(
connection(mysql,{
host: 'localhost',
user: 'root',
password : '',
port : null, //port mysql
database:'test'
},'request')
);
app.get('/api/entries', function(req, res){
req.getConnection(function(err, connection) {
if(err) {
console.log(err);
res.status(500).send('Cannot get database connection');
} else {
connection.query("select * from nodetest", function(err, rows) {
if(err) {
console.log(err);
res.status(500).send(err);
} else {
res.write(''+JSON.stringify(rows));
var date2 = (new Date()).getTime();
console.log('Cnt : '+rows.length+' Took Time to execute :'+(date2 - date1)/(60*60));
//console.log(rows);
//Now insert in another table ' nodetestcopy'
for(var i in rows){
connection.query("insert into nodetestcopy set ?", rows[i], function(err, rows) {
if(err) {
console.log(err);
//res.status(500).send(err);
} else {
}
});
}
}
});
}
});
});
app.listen(3000);
This script is working for the first time, and when I refresh the browser for second time, getting an error .
Please guide me what is going wrong here and also Is my approach is correct?
Looping the record for 50K times for(var i in rows){ ...}
Please give a feasible solution for this, and correct me wereever the code is wrong.
Thanks
What is the error message that you are getting? Also, another way to avoid hitting the database with multiple queries could be to combine the records in one query and then make one database insert call, like:
var query = 'insert into nodetestcopy values("';
for (var i in rows) {
query += rows[i] + '"';
if (i < rows.length) query += ',';
}
query += ')';
connection.query(query, function(err, rows) { ...