How to get data from another route (POST method)? - node.js

I have multiple routes setup. I want to get specific data from another route. That data is coming from a post method.
My server.js look like this:
var mysql = require('mysql')
var morgan = require('morgan')
var cors = require('cors')
var bodyParser = require('body-parser')
var http = require('http')
var dateFormat = require('dateformat')
const port = process.env.PORT || 3000;
//middleware
var app = express()
app.use(cors())
app.use(morgan('dev'))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}))
var now = new Date()
//routes
var user_details = require('./routes/users')
var user_orders = require('./routes/order')
//Use routes
app.use('/', user_details)
app.use('/', user_orders)
//Launch Server
app.listen(port, () => {
console.log('Server start at port: ' + port)
})
My routes/users.js :
var router = express.Router()
var db = require('../dbConfig')
var randomstring = require("randomstring");
var moment = require('moment')
router.post('/list', (req, res) => {
var appendRandomString = randomstring.generate({
length: 10,
capitalization: 'uppercase',
readable: true
})
var id = 'PEPPR_' + appendRandomString
var email = req.body.email
var listItems = req.body.listItems
var listTitle = req.body.listTitle
var date = moment().format("Do MMMM YYYY");
var time = moment().format("LT");
const INSERT_USER_LISTS = `INSERT INTO user_lists (id,date,time,user_email,list_title,list_items) VALUES('${id}','${date}','${time}','${email}','${listTitle}','${listItems}')`
db.query(INSERT_USER_LISTS, (err, success) => {
if (err) {
return res.send(err)
} else {
console.log('list added')
res.send('list added')
}
})
})
module.exports = router
And my routes/order.js
var router = express.Router()
var db = require('../dbConfig')
var randomstring = require("randomstring");
var moment = require('moment')
var user_details = require('./users')
router.post('/sendOrder', (req, res) => {
var email = req.body.email
var status = 'Order Confirmed'
var date = moment().format("Do MMMM YYYY");
var time = moment().format("LT");
var appendRandomString = randomstring.generate({
length: 10,
capitalization: 'uppercase',
readable: true
})
var id = 'PEPPR_ORDER_' + appendRandomString
var list_items = ''
var list_title = ''
var data = {
id: id,
email: email,
list_items: list_items,
list_title: list_title,
date: date,
time: time,
status: status
}
const CREATE_ORDER = `INSERT INTO user_orders SET ?`
db.query(CREATE_ORDER, data, (err, success) => {
if (err) {
return res.send(err)
} else {
res.send('oc')
}
})
})
module.exports = router
I want the list_items and list_title in my order.js from users.js , this two data is coming from a POST method as you can see in users.js

If I understood you correctly you want to use request body which comes to /users in another route /orders.
You are saving user data list_title and list_item in users table. So all you need to access the data from /orders route is make an additional query to db where you will select users by id\email.
Not sure which db ORM you use but in general cases your code may look like this:
router.post('/sendOrder', async (req, res) => {
const { email } = req.body;
// declare other fields
const user = await db.query(
`SELECT * FROM users WHERE email LIKE '%${email}%'`,
(err, success) => {
if (err) {
return res.send(err);
} else {
res.send('ok');
}
}
);
// declare `data` object with user.list_title, user.list_item
const CREATE_ORDER = `INSERT INTO user_orders SET ?`;
db.query(CREATE_ORDER, data, (err, success) => {
if (err) {
return res.send(err);
} else {
res.send('ok');
}
});
});

Related

Mongo Save function callback not triggering

Mongo save callback is not triggering, but the document is getting saved in the db, Heres my code:
MongoDb Version : 6.0.1
Mongoose Version : 6.8.2
The call back not returning anything, but the documents are getting saved without any issues, why the call back is not triggering?
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const url = 'mongodb://127.0.0.1:27017/musicapp';
const cors = require('cors');
var jquery = require('jquery');
//Mongodb
mongoose.connect(url, { useNewUrlParser: true });
mongoose.set('strictQuery', true);
var conn = mongoose.connection;
conn.on('connected', function () {
console.log("Database Connected");
})
var artistSchema = new mongoose.Schema({
artistName: String,
artistDob: String,
artistBio: String
})
const artists = mongoose.model("artist", artistSchema);
function addArtist(aName, aDOB, aBIO) {
const newArtist = new artists({
artistName: aName,
artistDob: aDOB,
artistBio: aBIO
})
newArtist.save((err, data, numAffected) => {
if (!err) {
return true;
}
else {
return false;
}
});
}
//MongoDb
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html")
})
app.post("/addsongs", cors(), (req, res) => {
console.log("Add songs");
})
app.post("/addartist", cors(), (req, res) => {
var artistName = req.body.modalartistname;
var artistDOB = req.body.modalartistdob;
var artistBio = req.body.modalartistbio;
var addedArtist = addArtist(artistName, artistDOB, artistBio);
if (addedArtist) {
res.sendStatus(200);
}
else {
console.log("Failure")
res.sendStatus(400);
}
//console.log("Artist Added Sucessfully");
})
app.listen(3000, function () {
console.log("The Server is up and running");
})

Middleware in router showing req.body empty, however in actual data does exist in post request

I am trying to access req.body in express middleware in a router, however it is consoling empty req.body. However in actual data does exist. I am already using body-parser at app level but it is not working for me. Below is my code, I am trying to access req.body in authorization middleware in categories.js file
index.js
const express = require('express');
const bodyParser = require('body-parser');
//Importing Routers
const customersRouter = require('./routes/customers');
const categoriesRouter = require('./routes/categories');
const itemsRouter = require('./routes/items');
const usersRouter = require('./routes/users');
const tablesRouter = require('./routes/tables');
const ridersRouter = require('./routes/riders');
const taxtypesRouter = require('./routes/taxtypes');
const branchesRouter = require('./routes/branches');
const subscribeRouter = require('./routes/subscription');
const loginRouter = require('./routes/login');
//Importing Database Connection
//const db = require('./dbConnection');
const app = express();
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server is listening at port ${PORT}`));
app.use('/subscribe', subscribeRouter);
app.use('/login', loginRouter);
app.use('/client/:clientID/user/:userID/customers', customersRouter);
app.use('/:clientID/categories', categoriesRouter);
app.use('/client/:clientID/user/:userID/items', itemsRouter);
app.use('/client/:clientID/user/:userID/users', usersRouter);
app.use('/client/:clientID/user/:userID/tables', tablesRouter);
app.use('/client/:clientID/user/:userID/riders', ridersRouter);
app.use('/client/:clientID/user/:userID/taxtypes', taxtypesRouter);
app.use('/client/:clientID/user/:userID/branches', branchesRouter);
router file categories.js
const express = require('express');
const util = require('util');
const categoriesRouter = express.Router();
const verifyToken = require("../functions/userVarification");
const multer = require('multer');
const fs = require('fs');
var path = require('path');
//Importing Database Connection
const db = require('../dbConnection');
const query = util.promisify(db.query).bind(db);
// File Uploading through Multer
var storage = multer.diskStorage({
destination: (req, file, cb) => {
const path = `./uploads/${req.body.clientID}/categories`;
fs.mkdirSync(path, { recursive: true });
return cb(null, path);
},
filename: function (req, file, cb) {
cb(null, req.body.clientID + "_" + "Category_" + file.originalname.replace(".", "_") +"_" + Date.now() + path.extname(file.originalname)) //Appending extension
}
})
var upload = multer({ storage: storage });
function authorization(req, res, next) {
//Only Admins are allowed to add category
const roleID = parseInt(req.authData.roleID);
if (roleID !== 1) res.status(403).json({ msg: "Sorry your are not authorized to add categories" });
else {
next();
}
}
categoriesRouter.post('/', verifyToken, (req, res, next) => authorization(req, res, next), upload.single('Image'), (req, res) => {
//destructuring request body
const clientID = parseInt(req.body.clientID);
const userID = parseInt(req.body.userID);
const name = req.body.Name;
const branches = req.body.Branches;
const color = req.body.Color;
let imageSource = `uploads/${req.body.clientID}/categories/${req.file.filename}`;
const imageInPOS = req.body.ImageInPOS;
const visibilityInPOS = req.body.VisibilityInPOS;
try {
(async () => {
//Create Local Category ID
const SQL1 = `SELECT COUNT(ClientID) AS 'Categories' FROM categories WHERE ClientID = ${clientID};`;
let counter = await query(SQL1);
counter = counter[0].Categories + 1;
const localCategoryID = 'CT' + ('00' + counter).slice(-3);
//SQL for Adding Category in the database
const SQL2 = `INSERT INTO categories (CategoryID, LocalCategoryID, ClientID, CategoryName, ShowInBranches, CategoryColor, ImageSrc, DisplayInPOS, DisplayImage)
VALUES (NULL, '${localCategoryID}', ${clientID}, '${name}', '${branches}', '${color}', '${imageSource}', ${visibilityInPOS}, ${imageInPOS})`;
const addedCategory = await query(SQL2);
if(addedCategory.affectedRows > 0) {
res.status(200).json({ msg : "Category have been added"});
}
else {
res.status(500).json({ msg: "Something went wrong" });
}
})()
}
catch (err) {
res.status(500).json({ msg: "Something went wrong" });
return;
}
});
module.exports = categoriesRouter;
the body-parser module don't require to explicitly install.
Its provided under the methods express.json() and express.urlencoded().
so add
app.use(express.urlencoded({extended: true}));
app.use(express.json())
and remove
require('body-parser');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

req.body undefined...how can i solve

[ server.js ]
const fs = require("fs");
const express = require("express");
const bodyParser = require("body-parser");
const mysql = require("mysql");
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
const data = fs.readFileSync("./database.json");
const conf = JSON.parse(data);
const connection = mysql.createConnection({
host: conf.host,
user: conf.user,
password: conf.password,
port: conf.port,
database: conf.database
});
connection.connect();
app.get("/api/users", (req, res) => {
connection.query(
"select * from users where isDeleted = 0",
(err, rows, fields) => {
res.send(rows);
// console.log(err);
// console.log(rows);
}
);
});
app.post("/api/users", (req, res) => {
let sql = "insert into users values (null,?,?,now(),now(),0)";
let name = req.body.name;
let dsc = req.body.dsc;
let params = [name, dsc];
console.log(params);
connection.query(sql, params,
(err, rows, fields) => {
res.send(rows);
// console.log(err);
// console.log(rows);
});
});
app.delete("/api/users/:id", (req, res) => {
let sql = "update users set isDeleted = 1 where id = ?";
let params =[req.params.id];
connection.query(sql,params,
(err, rows, fields)=>{
res.send(rows);
// console.log(err);
// console.log(rows);
});
});
app.listen(port, () => console.log(`Listening on port http://localhost:${port}`));
Describe the bug
I am trying to send form data to my API but req.body is undefined for some reason.
To Reproduce
Steps to reproduce the behavior:
create a new request
enter your API endpoint URL
select the body tab and then select the form-data tab
enter the key name of the form data you are trying to send so your API can recognize it and then the value.
Click send and you should get a response with a status code of 200. If you get an error like me telling me that req.body is undefined then you have the same problem as me.
You are using bodyparser.json(). From the documentation, this will parse requests that are only in JSON. You are better off using bodyParser.urlencoded([options]).
I advise using express.urlencoded instead.
Read this for clarification
you are missing the router
[ server.js ]
const fs = require("fs");
const express = require("express");
const bodyParser = require("body-parser");
const mysql = require("mysql");
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
const data = fs.readFileSync("./database.json");
const conf = JSON.parse(data);
const connection = mysql.createConnection({
host: conf.host,
user: conf.user,
password: conf.password,
port: conf.port,
database: conf.database
});
connection.connect();
// u need a router
const router = express.Router();
router.get("/api/users", (req, res) => {
connection.query(
"select * from users where isDeleted = 0",
(err, rows, fields) => {
res.send(rows);
// console.log(err);
// console.log(rows);
}
);
});
router.post("/api/users", (req, res) => {
let sql = "insert into users values (null,?,?,now(),now(),0)";
let name = req.body.name;
let dsc = req.body.dsc;
let params = [name, dsc];
console.log(params);
connection.query(sql, params,
(err, rows, fields) => {
res.send(rows);
// console.log(err);
// console.log(rows);
});
});
router.delete("/api/users/:id", (req, res) => {
let sql = "update users set isDeleted = 1 where id = ?";
let params =[req.params.id];
connection.query(sql,params,
(err, rows, fields)=>{
res.send(rows);
// console.log(err);
// console.log(rows);
});
});
app.use(router);
app.listen(port, () => console.log(`Listening on port http://localhost:${port}`));

Get "undefined" for req.session in nodejs

Noob here, and I tried to have a session to do the login attempt count in nodejs, but it seem the session is not declared in route as it just show undefined when i console.log it.
Below is my code :
Server.js
var express = require('express');
var session = require('express-session');
var cors = require('cors');
var bodyParser = require("body-parser");
var app = express();
var port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(cors());
app.use(session({ resave: false, saveUninitialized: true, secret: 'onemonkey', cookie: { secure: false }}));
app.use(bodyParser.urlencoded({
extended: false
}));
var Users = require('./Routes/Users');
app.use('/users',Users);
app.listen(port,function(){
console.log("Server is running on port: "+port);
});
in users.js
var express = require('express');
var users = express.Router();
var database = require('../Database/database');
var cors = require('cors')
var jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
//var request = require('request');
var token;
users.use(cors());
users.post('/login', function(req, res) {
var appData = {};
var email = req.body.email;
var password = req.body.password;
let someRows, otherRows;
let token;
var databaseQuery = new database.DatabaseQuery();
databaseQuery.beginTransaction()
.then (() => {
return databaseQuery.query('SELECT * FROM users WHERE email = ? AND status = ?', [email, 'active'])
})
.then( rows => {
someRows = rows;
if (someRows.length > 0) {
bcrypt.compare(password, someRows[0].password).then(function(ret) {
// res == true
if(ret){
//when validate successfully
}else{
console.log(req.session[email]);
req.session[email] = req.session[email] + 1;
req.session.save();
console.log('--------login-----');
console.log(req.session[email]);
if(req.session[email] == 3){
databaseQuery.query('update users set status=? where email=?',['block',email])
.then( rows => {
otherRows = rows;
var user_status = {
contact_id : someRows.insertId,
remark : "3 times login attempt fail",
status : "block",
edit_by : "SYSTEM"
}
return databaseQuery.query( 'INSERT INTO user_status_detail SET ?', [user_status] );
}).then ( rows =>{
appData.error = 1;
appData["data"] = "Email account blocked";
req.session[email] = null;
req.session.save();
res.status(200).json(appData);
return databaseQuery.commit();
}, err => {
return databaseQuery.close.then( () => { throw err; } )
})
}else{
//record not match
}
}
});
}else {
//account not exist
}
})
.catch( err => {
//err handling
} )
});
module.exports = users;
I tried to store the count in req.session[email] in user.js, and block the email once the count equal to 3. However, it not storing the count and showing undefined every time i tried to login which wrong password.
Highly appreciate your advise on it.
add these lines to the top :
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

MEAN API using node-restful no response

I'm trying to setup API for multiple projects that use same database structure (running on same CMS) but when I'm trying to reach some data I get no response.
index.js
var express = require("express");
var cors = require("cors");
var mongoose = require("mongoose");
var bodyParser = require("body-parser");
var methodOverride = require("method-override");
var _ = require("lodash");
var passport = require("passport");
var dbconfig = require("./app/config/database");
// Create the application
var app = express();
var user = require("./app/routes/User");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(methodOverride('X-HTTP-Method-Override'));
var connections = [];
// Auto CORS
app.use(cors());
/* Mnual CORS Start
app.use(function(req, res, next){
res.header("Access-Controll-Allow-Origin", "*");
res.header("Access-Controll-Allow-Methods", "GET,PUT,POST,DELETE");
res.header("Access-Controll-Allow-Headers", "Content-Type");
next();
});
/* Manual Cords end */
// Passport Middleware
app.use(passport.initialize());
app.use(passport.session());
require("./app/config/passport")(passport);
app.get("/", (req, res) => {
res.json({ msg: "Nothing here mate" });
});
//------------ THIS IS WORKING ----------------
app.get("/db/:database/navigation", (req, res) => {
var dbname = req.params.database;
var conn = connections[dbname];
var navs = conn.model("navigation", app.models[dbname].navigation);
// Send json data/error
if (navs) navs.find({}, (err, data) => res.json(data));
else res.json({ error: true, msg: "Model not found" });
});
// -------------------------------------------------------
// Setup databases for all projects
_.each(dbconfig.databases, db => {
var appModels = require("./app/models/index");
var processed = 0;
// We will use prefix for all routes /db/:database/
var routePrefix = "/db/" + db.name;
// Use user section
app.use(routePrefix + "/user", user);
// Connection callback - we need to wait for modules to initialize
var connect = () => {
// Initialize connection
connections[db.name] = new mongoose.Mongoose().createConnection(db.url);
// Create some callbacks
connections[db.name].on("connected", () => { console.log("Connected to database " + db.url); });
connections[db.name].on("error", onDatabaseError)
// Once we initialize connection, we need to setup all routes
connections[db.name].once("open", function () {
// Load routes
var routes = require('./app/routes');
// Loop trough routes and use all of them
_.each(routes, function (controller, route) {
var newRoute = routePrefix + route;
app.use(newRoute, controller(app, newRoute, db.name));
});
});
};
// Initialize models
_.each(appModels, (model, index) => {
// Create object if doenst exist
if (app.models == null)
app.models = {};
if (app.models[db.name] == null) {
app.models[db.name] = { [model.name]: model.model };
}
else {
app.models[db.name] = Object.assign(app.models[db.name], { [model.name]: model.model });
}
processed++;
// if this was the last process we are ready to connect
if (processed === appModels.length)
connect();
});
});
app.listen(3000);
app/models/index.js
module.exports = [
{
name: "navigation",
model: require('./Navigation.js')
},
...
];
app/routes.js
module.exports = {
'/navigation': require('./controllers/NavigationController'),
....
};
app/controllers/NavigationController.js
var restful = require("node-restful");
module.exports = function(app, route, dbname){
console.log(route);
var rest = restful.model(
"navigation",
app.models[dbname].navigation
).methods(['get', 'put', 'post', 'delete']);
rest.register(app, route);
// Return middleware
return function(req, res, next){
next();
};
};
Navigation.js is basically just a schema. If I set up route manually like this:
app.get("/db/:database/navigation", (req, res) => {
var dbname = req.params.database;
var conn = connections[dbname];
var navs = conn.model("navigation", app.models[dbname].navigation);
// Send json data/error
if (navs) navs.find({}, (err, data) => res.json(data));
else res.json({ error: true, msg: "Model not found" });
});
it works just fine. I guess I need to assign connection somewhere to restful but I have no idea where. If I use single connection with mongoose.connect() everything works perfectly, but that's not what I need :)
Does anyone have any idea what to do next to get this to work? Will appreciate any help, thanks.
Kind of dug into it and made an extension to change driver reference
Here are all the changes, hope it helps someone in future :)
extensions/restful/index.js
var restful = require("node-restful"),
model = require("./model"),
mongoose = require('mongoose');
exports = module.exports = restful;
exports.model = model;
exports.mongoose = mongoose;
extensions/restful/model.js
exports = module.exports = model;
exports.changeDriver = function(driver){
mongoose = driver;
}
// original model function from node-restful/lib/model.js
function model() {
var result = mongoose.model.apply(mongoose, arguments),
default_properties = defaults();
if (1 === arguments.length) return result;
for (var key in default_properties) {
result[key] = default_properties[key];
}
return result;
}
app/controllers/navigation.js
var restful = require("../extensions/restful");
module.exports = function(app, route, db)
{
restful.model.changeDriver(db.mongoose);
// Setup controller REST
var rest = restful.model(
"navigation",
app.models[db.name].navigation
).methods(['get', 'put', 'post', 'delete']);
// Register this endpoint with the application
rest.register(app, route);
// Return middleware
return function(req, res, next){
next();
};
};
index.js
....
var connect = () => {
// Initialize connection
var $db = databases[_db.name] = {
mongoose: new mongoose.Mongoose(),
name: _db.name
};
$db.mongoose.connect(_db.url);
// Create some callbacks
$db.mongoose.connection.on("connected", () => { console.log("Connected to database " + _db.url); });
$db.mongoose.connection.on("error", (err) => { console.log("Database error: " + err); });
// Once we initialize connection, we need to setup all routes
$db.mongoose.connection.once("open", function () {
// Custom routes for user section
var userRoutes = new UserRoutes($db.mongoose);
app.use(routePrefix + "/user", userRoutes.getRouter());
// Load routes
var routes = require('./app/routes');
// Loop trough routes and use all of them
_.each(routes, function (controller, route) {
var newRoute = routePrefix + route;
app.use(newRoute, controller(app, newRoute, $db));
});
});
};
....

Resources