I would like to get an 'articlePageId' number from url as below, but the terminal window did not show the URL query parameters...
What's the matter with my coding?
Could anyone tell me how can I do that??
Thank you very much.
I have tried the following:
https://localhost:8090/articlePage.html?articlePageId='+item.ID
console.log(fullUrl) // http://localhost:8090/
console.log(req.path) // /
console.log(req.params) // {}
console.log(req.query.articlePageId) // undefined
Here is the Server
const express = require('express');
const expressStatic = require('express-static')
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const multer = require('multer');
const multerObj = multer({dest:'./static/upload'});
const consolidate = require('consolidate');
const server = express();
server.use(bodyParser.urlencoded({extended:true}));
server.use(multerObj.any());
server.use(cookieParser());
(function(){
const keys = [];
for(var i=0;i<1100000;i++){
keys[i] = 's_' + Math.random();
}
server.use(cookieSession({
keys,
name:'sess_id',
maxAge:20*60*1000
}));
})()
server.engine('html',consolidate.ejs);
server.set('views','template');
server.set('view engine','html');
server.use('/',require('./router/web/index')());
server.use('/admin',require('./router/admin/index')());
server.use(expressStatic('./static/'))
server.listen(8090)
Here is the index.js
router.use('/', require('./articlePage')())
Here is the articlePage.js
var express = require('express');
var mysql = require('mysql');
var urlLib = require('url');
var querystring = require('querystring')
var db = mysql.createPool({
localhost: 'localhost',
user: 'root',
password: '123456',
database: 'blog'
})
module.exports = () => {
var router = express.Router();
router.get('/', (req, res) => {
var fullUrl = req.protocol + '://' + req.get('host') +req.originalUrl;
console.log(fullUrl)
console.log(req.path)
console.log(req.params)
console.log(req.query.articlePageId)
db.query(`SELECT * FROM articles_table WHERE ID='articlePageId'`, (err, page) =>
{
if (err) {
console.error(err);
res.status(500).send('database error').end();
} else {
res.send(page);
}
})
})
return router
}
Related
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());
I have been getting a problem when I want to module.export the pool variable to use it in other files. I have this program in src\db\index.js:
const {Pool} = require('pg');
const express = require('express');
//Initialize
const path = require('path');
const app = express();
const fetch = require('fetch');
const PORT = process.env.PORT || 5000;
//Global Variables
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl:true
});
//Setting
app.use(express.static(path.join(__dirname, 'public')));
//Routes
app.use(require('../Routes/logIn'));
app.use(require('../Routes/singIn'));
app.use(require('../Routes/forgotPass.js'));
app.listen(PORT, () => console.log(`Listening on ${PORT}`));
module.exports = pool;
And then I want to require the const pool in this file src\Routes\LogIn.js:
const express = require('express');
const pool = require('../db');
const router = express.Router();
router.get('/usuario/:user', function (req, res) {
//console.log("GET usuario");
var user = req.params.user;
pool.query(
`select * from users where email = '${user}' limit 1`,
function (error, resq, fields) {
if (error) {
console.log(error);
} else {
console.log(user);
res.send(resq.rows);
}
}
);
});
module.exports = router;
But when I run the index.js and go to the route ulr/usuario/:user, in the logs I see that the program has an error that says "pool.query is not a function". I want to know how i could export the const pool to use it in other files.
You can use
module.exports = {
query: (text, params) => pool.query(text, params),
}
Use express-promise-router
const Router = require('express-promise-router')
const db = require('../db')
const router = new Router()
Use
await db.query(`
SELECT * from local
`)
instead of pool.query in your router.get or router.post
The above should solve your issue - You can check the same reference here
https://node-postgres.com/guides/async-express
I have created a service in node.js for basic crud operations. However when I start service it throws Route.get() requires a callback function but got a [object Undefined] error. I am not able to figure out where the error is.
Here is my code.
Models:
agreement_master.js.
const mongoose = require('mongoose');
const agreementmaster = mongoose.Schema({
ClientId:{type:Number},
UserId:{type:Number},
StartDate:{type:Date},
});
var Agreement = module.exports =
mongoose.model('Agreement',agreementmaster);
module.exports.addmAgreement=function (data,callback){
data.save(callback);
}
module.exports.getallmAgreement= function (data,callback){
var query = {status:true};
Agreement.find(query, callback);
}
routes:
agreement_master.js
var express = require('express'),
router = express.Router(),
magreement = require('../controller/agreement_master');
router.post('/addmAgreement', magreement.addmAgreement);
module.exports = router;
Controller:
agreement_master.js
const Agreement= require('../models/agreement_master');
exports.addmAgreement = function (req, res){
var data = JSON.parse(JSON.stringify(req.body));
var agreement = new Agreement(data);
agreement.ClientId = req.body.ClientId;
agreement.UserId= req.body.UserId;
agreement.StartDate=new Date();
Agreement.addmAgreement(agreement, function (err, obj) {
if (err) return res.json({err, status:'error'});
if(obj){
return res.json({
message:'agreement added',
});
}
});
};
index.js
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const expressValidator = require('express-validator');
const cookieParser = require('cookie-parser');
mongoose.connect('mongodb://local/local-host')
const app = express();
error comes at this part in the below line:
const agreement = require('./routes/agreement_master');
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(expressValidator());
app.use(cookieParser());
//Add Routes here
app.use('/agreement', agreement);
app.set('port', (process.env.PORT || 3001));
var server = app.listen(app.get('port'), function(){
console.log('Server Started on port ' + app.get('port'));
});
module.exports = app;
user module.exports instead of exports.
exports doest export anything and will not be used by require();
module.exports.addmAgreement = function (req, res){
var data = JSON.parse(JSON.stringify(req.body));
var agreement = new Agreement(data);
agreement.ClientId = req.body.ClientId;
agreement.UserId= req.body.UserId;
agreement.StartDate=new Date();
Agreement.addmAgreement(agreement, function (err, obj) {
if (err) return res.json({err, status:'error'});
if(obj){
return res.json({
message:'agreement added',
});
}
});
};
try this
router.post('/addmAgreement', function(req, res){
magreement.addmAgreement
});
instead of
router.post('/addmAgreement', magreement.addmAgreement);
I have a site, implemented on NodeJS, base MongoDB, Mongoose plugin. Recently, the site began to fall about once a day. I recently found out that this is due to the lack of memory, which is due to the fact that active connections are being accumulated (db.serverStatus (). Connections.current). Perhaps this is not related, but I have a script on NodeJS, which is executed by crown every minute. It checks if there is a post with the current date in the documents. But I close the mongoose connection there, I don’t know what could be the problem. Actually this file contents:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
const { new_time } = require("lib/functions");
const push = require("lib/push");
const apiCallback = require("middleware/socket/apiCallback");
const mongoose = require("lib/mongoose");
const User = require("models/User");
const Post = require("models/Post");
(async () => {
let currentPost = await Post.findCurrent(1);
if (currentPost) {
await currentPost.setPublished(1);
await apiCallback.call({
roomName: "index",
event : "posts.new",
data : {
post: {
id: currentPost._id.toString()
}
}
});
await push.sendAll({
// unnecessary data
});
}
await mongoose.connection.close();
process.exit(0);
})();
app.js:
const path = require("path");
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const expressSession = require("express-session");
const MongoStore = require("connect-mongo")(expressSession);
const conf = require("conf");
const mongoose = require("lib/mongoose");
const expressSessionConfig = conf.get("session");
expressSessionConfig.cookie.expires = new Date(new Date().getTime() + 60 * 60 * 24 * 30 * 1000);
expressSessionConfig.store = new MongoStore({
mongooseConnection: mongoose.connection
});
const templateDir = path.join(__dirname, conf.get("template_dir"));
app.engine("ejs", require("ejs-locals"));
app.set("views", templateDir);
app.set("view engine", "ejs")
app.use(express.static("frontend"));
app.use(cookieParser());
app.use(expressSession(expressSessionConfig));
app.use(bodyParser.urlencoded({
extended: true
}));
require("routes")(app);
app.listen(conf.get("app_port"));
app.io.js (socket server on socket.io):
const fs = require("fs");
const path = require("path");
const app = require("express")();
const bodyParser = require("body-parser");
const apiCallback = require("middleware/socket/apiCallback");
const conf = require("conf");
const sslPath = conf.get("sslPath");
const sslOptions = {
key : fs.readFileSync(path.join(sslPath, "key.key")),
cert: fs.readFileSync(path.join(sslPath, "crt.crt"))
};
const server = require("https").Server(sslOptions, app);
const io = require("socket.io")(server);
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(conf.get("api_callback:path"), apiCallback.watch(io));
require("routes/socket")(io);
server.listen(conf.get("socket_port"));
routes/socket.js:
const { in_array } = require("lib/functions");
const loadUser = require("middleware/socket/loadUser");
const User = require("models/User");
module.exports = io => {
io.on("connection", async socket => {
let query = socket.handshake.query || {};
let { ssid } = query;
ssid = ssid || "";
let user = socket.user = await loadUser(ssid);
let oldPageName = null;
User.setOnline(user._id, 1);
socket.on("setPageName", pageName => {
if (oldPageName) socket.leave(oldPageName);
oldPageName = pageName;
socket.join(pageName);
});
socket.on("disconnect", () => {
socket.leave(oldPageName);
User.setOnline(user._id, 0);
});
});
};
Tell me how to properly close connections so that they do not remain in memory and do not load the server to such an extent that it kills the process of the MongoDB daemon?
your code has no issues, you should go for connection pooling. your issue would automatically resolve. you will have a pool of connections whenever any api needs a db conenction. connection would be picked up from the pool and after completing db operation connection wouldn't be destroyed instead it would be returned back to the pool, in this manner your product's performance would be increased along with resolution to this issue.
https://mongoosejs.com/docs/connections.html
i'm new to the forum and i've been doing a project for my university and i got a problem with my post request. Can anyone help me with this?
I'm using express and mongo.
Here's my code:
server.js
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var methodOverride = require('method-override');
var app = express();
app.use(cors());
const port = 3000;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
mongoose.connect('mongodb://localhost/futbol', { useMongoClient: true });
require('./Modelos/partidos.js');
app.use(require('./Rutas'));
var router=express.Router();
app.use(router);
app.listen(port, () => {
console.log('We are live on ' + port);
});
index.js
var router=require('express').Router();
router.use('/api/partidos', require('./partidos'));
module.exports=router;
partidos.js
var mongoose = require('mongoose');
var router = require('express').Router();
var bodyParser = require('body-parser');
var Partido = mongoose.model('partido');
// GET ALL
router.get('/', (req, res, next) => {
Partido.find({})
.then(partidos => {
if(!partidos){ return res.sendStatus(401); }
return res.json({'partidos': partidos})
})
.catch(next);
});
// GET BY ID
router.get('/:_id', (req, res, next) => {
let _id = req.params._id
Partido.findById(_id)
.then(partidos => {
if(!partidos){ return res.sendStatus(401); }
return res.json({'partidos': partidos})
})
.catch(next);
});
// POST PARTIDO
router.post('/', (req, res, next) => {
var _id = req.body._id;
var id_equipo1 = req.body.id_equipo1;
var nombre_equipo1 = req.body.nombre_equipo1;
var id_equipo2 = req.body.id_equipo2;
var nombre_equipo2 = req.body.nombre_equipo2;
var fecha_inicio = req.body.fecha_inicio;
var hora_inicio = req.body.hora_inicio;
res.send("post _id: "+_id+" - id_equipo1: "+id_equipo1+" - nombre_equipo1 "+nombre_equipo1+" - id_equipo2 "+id_equipo2+" - nombre_equipo2 "+nombre_equipo2+" - fecha_inicio "+fecha_inicio+" - hora_inicio "+hora_inicio);
});
module.exports=router;
The POST method that is throwing an error is in partido.js
I'm also using RestEasy to make my post request with this parameters:
Url: http://localhost:3000/api/partidos
Method: POST
Headers: Content-Type: application
Body:
{
"_id" : "2",
"id_equipo1" : "4",
"nombre_equipo1" : "Independiente",
"id_equipo2" : "5",
"nombre_equipo2" : "River",
"fecha_inicio" : "10/10/17",
"hora_inicio" : "21:00:00"
}
This is the result:
{
post _id: undefined,
id_equipo1: undefined,
nombre_equipo1: undefined,
id_equipo2: undefined,
nombre_equipo2: undefined,
fecha_inicio: undefined,
hora_inicio: undefined
}
Thanks in advance!