Access Body Param NodeJS Express - json

I have a route
router.post('/api/getSessionTimeOut', apiController.getSessionTimeOut);
This is in my controller
function getSessionTimeOut(req, res) {
res.send(req.body.session); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
var options =
{
method: 'POST',
url: 'http://api/json',
body:
{
id: 1,
method: 'get',
params: [
{
url: '/cli/global/system/admin/setting'
}
],
session: req.params.session
},
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body, response);
res.send(response.result);
});
};
After making a POST to the route with session as body via Postman
I kept getting
Red alert! Red alert!: TypeError: Cannot read property 'session' of undefined
at getSessionTimeOut (/Users/doe/Desktop/express-app/controllers/api.js:50:23) at Layer.handle [as handle_request] (/Users/doe/Desktop/express-app/node_modules/express/lib/router/layer.js:95:5) at next (/Users/doe/Desktop/express-app/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/Users/doe/Desktop/express-app/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/Users/doe/Desktop/express-app/node_modules/express/lib/router/layer.js:95:5) at /Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:281:22 at Function.process_params (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:335:12) at next (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:275:10) at Function.handle (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:174:3) at router (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:47:12) at Layer.handle [as handle_request] (/Users/doe/Desktop/express-app/node_modules/express/lib/router/layer.js:95:5) at trim_prefix (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:317:13) at /Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:284:7 at Function.process_params (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:335:12) at next (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:275:10) at serveStatic (/Users/doe/Desktop/express-app/node_modules/serve-static/index.js:75:16) at Layer.handle [as handle_request] (/Users/doe/Desktop/express-app/node_modules/express/lib/router/layer.js:95:5) at trim_prefix (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:317:13) at /Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:284:7 at Function.process_params (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:335:12) at next (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:275:10) at expressInit (/Users/doe/Desktop/express-app/node_modules/express/lib/middleware/init.js:40:5)
index.js
import express from 'express'
import favicon from 'serve-favicon'
import path from 'path'
import bodyParser from 'body-parser'
// Controllers
import apiController from './controllers/api'
const router = express.Router();
const app = express();
const PORT = 3000;
//For public folder
app.use(express.static('public'))
app.use(router)
app.use('/images',express.static('images'))
app.use(favicon(path.join(__dirname,'public','favicon.ico')))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
router.get('/', (req,res) => {
res.send('Welcome to the backend provisioning daemon to program FortiManager')
});
// app.use( express.json());
app.use(express.urlencoded({extended: true}))
app.set('trust proxy', 'loopback');
//Fortinet
router.post('/api/getSessionTimeOut', apiController.getSessionTimeOut);
router.post('/api/login', apiController.login);
//Error handling function
app.use((err,req,res,next) => {
console.error(err.stack)
res.status(500).send(`Red alert! Red alert!: ${err.stack}`)
});
// app listen
app.listen(PORT, () => {
console.log(`Your server is running on ${PORT}`)
}
);

Try moving
app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true }));
right after
const app = express();
Why, because you need to use/register middlewares on your server/app before registering any route on your server. This will make sure that every request coming to the registered route is first passed through body-parsers and will let the body-parsers to do the construct the request data in its specified data structure or format.
Hope that helps
Thanks

Related

Why is Knex not able to insert into mysql?

I am trying to insert a row of values into MySQL database using Knex but I am getting a weird error. The table and database exist and the fetch API works perfectly but I am not able to insert values using sifnUp route.
const db= knex ({
client: 'mysql2',
connection: {
host: '127.0.0.1',
port: 3306,
user: 'root',
password: '',
database: 'transaction_app'
}
});
app.get('/', (req, res) => {
res.send('App is running')
});
app.post('/signUp', (req, res,db) => {
const {name, email, mobile, password}=req.body;
const hash=bcrypt.hashSync(password, 10);
db('users')
.insert({
name: name,
email: email,
mobile: mobile,
password: hash
})
.then(data=>{
res.send(data);
})
.catch(err=>{
res.send(err);
})
});
app.get('/fetch',(req,res)=>{
db.select('*').from('users')
.then(data=>{
res.send(data);
})
.catch(err=>{
res.send(err);
})
})
app.listen(3000, () =>{
console.log('Server started on port 3000');
});
The error that is consoled is this
Server started on port 3000
users
TypeError: Cannot read properties of undefined (reading 'insert')
at D:\Documents\Atoa Assignment\server.js:35:3
at Layer.handle [as handle_request] (D:\Documents\Atoa Assignment\node_modules\express\lib\router\layer.js:95:5)
at next (D:\Documents\Atoa Assignment\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (D:\Documents\Atoa Assignment\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (D:\Documents\Atoa Assignment\node_modules\express\lib\router\layer.js:95:5)
at D:\Documents\Atoa Assignment\node_modules\express\lib\router\index.js:284:15
at Function.process_params (D:\Documents\Atoa Assignment\node_modules\express\lib\router\index.js:346:12)
at next (D:\Documents\Atoa Assignment\node_modules\express\lib\router\index.js:280:10)
at cors (D:\Documents\Atoa Assignment\node_modules\cors\lib\index.js:188:7) at D:\Documents\Atoa Assignment\node_modules\cors\lib\index.js:224:17
This is the Postman Screenshot.
Your error:
app.post('/signUp', (req, res,db) => {
const {name, email, mobile, password}
The third parameter is the express next, not db.
Inside the route you assign next() to db. (req,res,"db")
Must be (req,res, next).
When you call db.insert it is not referring of the top of your code
const db= knex ({
So you dont db.insert but next.insert (which obviously does not exist).
As you are not using the next handler of express, simply delete db in (req,res,db) and it should work.
Remember the scopes of variables in Javascript.
An Example

Cannot read property 'jwtoken' of undefined

here I generate the token at backend in express
..............
router.post("/login",async(req,res)=>{
const {email,password}=req.body;
if(!email || !password){
return res.status(401).send({error:"please filled the data properly"});
}
try {
const loginUser=await User.findOne({email:email});
if(!loginUser){
return res.status(400).send({error:"not found"});
}
const isMatch = await bcrypt.compare(password,loginUser.password);
if(isMatch){
const token=await loginUser.generateToken();
res.cookie("jwtoken",token,{
expires:new Date(Date.now()+15000000),
httpOnly:true,
//secure:true //it is applicable when we use https method
})
console.log(token);
res.send({message:"login success"});
}else{
res.status(400).send({error:"please enter correct data"})
}
} catch (error) {
res.status(400).send(error)
}
})
the token is create when i login in brouser
here is the about page (react)
...................
const verifyPage=async()=>{
try{
const res=await fetch('/about',{
method:"GET",
headers:{
Accept:"application/json",
"Content-Type":"application/json"
},
credentials:"include"
});
const data=await res.json();
console.log(data);
if(!res.status===200){
const err=new Error(res.error);
throw err;
}
}catch(err) {
console.log(err);
history.push("/login");
}
}
useEffect(()=>{
verifyPage();
},[])
.............
here I verify the token
...........
router.get("/about",Authentication,(req,res)=>{
res.send(req.rootUser);
})
........
The authentication page
............
const jwt = require("jsonwebtoken")
const User=require("../models/shegma")
const Authentication=async (req,res,next)=>{
try{
const token=req.cookies.jwtoken;
console.log(token)
const verifyToken=jwt.verify(token,process.env.TOKENID);
console.log(verifyToken);
const rootUser=await User.findOne({_id:verifyToken._id,"tokens.token":token})
if(!rootUser){throw new Error("user not found")}
req.token=token;
req.rootUser=rootUser;
req.userID=rootUser._id;
next();
}catch(err){
res.status(401).send("no token found");
console.log(err);
}
}
module.exports=Authentication;
..........
here is the error
......
TypeError: Cannot read property 'jwtoken' of undefined
at Authentication (C:\Users\ASUS\Desktop\mern\server\middleware\Authentication.js:6:33)
at Layer.handle [as handle_request] (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\index.js:47:12)
At first, you need to install cookie-parser inside your server folder
npm i cookie-parser
Then, require cookie-parser inisde that .js file where you have initialized express
const cookieParser = require('cookie-parser')
After this, below const app = express(); just write
app.use(cookieParser())
Here is the full code:-
const express = require('express');
const cookieParser = require('cookie-parser')
const app = express();
app.use(cookieParser())
Do you happen to be parsing the cookies on the incoming request anywhere in your express code?
The req.cookies object being undefined leads me to believe you may not be parsing the request for cookies or that the parsing is not happening before the Authentication handler is called.
For reference: express cookie-parser

nodejs form cannot read property 'docreate' of undefined

I'm a new in nodejs, and trying to create a new MVC application with expressjs. I have a html form with "POST" method and when i submit that some error showing.
Cannot read property 'docreate' of undefined
TypeError: Cannot read property 'docreate' of undefined
at exports.save (C:\Users\Hieu Vo\Desktop\hellow\notes\routes\notes.js:13:18)
at Layer.handle [as handle_request] (C:\Users\Hieu Vo\Desktop\hellow\notes\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Hieu Vo\Desktop\hellow\notes\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\Hieu Vo\Desktop\hellow\notes\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\Hieu Vo\Desktop\hellow\notes\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Hieu Vo\Desktop\hellow\notes\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\Hieu Vo\Desktop\hellow\notes\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\Hieu Vo\Desktop\hellow\notes\node_modules\express\lib\router\index.js:275:10)
at expressInit (C:\Users\Hieu Vo\Desktop\hellow\notes\node_modules\express\lib\middleware\init.js:40:5)
at Layer.handle [as handle_request] (C:\Users\Hieu Vo\Desktop\hellow\notes\node_modules\express\lib\router\layer.js:95:5)
here is app.js file
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var notes = require('./routes/notes');
var app = express();
// view engine setup
app.use('/noteadd', notes.add);
app.post('/notesave', notes.save);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(logger('dev'));
app.use(express.json());
app.post('/', function(request, response){
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// 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');
});
module.exports = app;
I have view file with name noteedit.ejs
<% include top %>
<p value='<%= docreate ? "create" : "update"%>'><%= docreate ? "create" : "update"%></p>
<form method='POST' action='/notesave'>
<input type='hidden' name='docreate' value='<%= docreate ? "create" : "update"%>'>
<p>Key: <input type='text' name='notekey' value='<%= note ? notekey : "" %>'></p>
<p>Title: <input type='text' name='title' value='<%= note ? note.title : "" %>'></p>
<br/>
<textarea rows=5 cols=40 name='body'><%= note ? note.body : "" %></textarea>
<br/>
<input type='submit' value='Submit' />
</form>
<% include bottom %>
and this is my save function
var notes = require('../models/notes');
exports.add = function(req, res, next) {
res.render('noteedit', {
title: "Add a note",
docreate: true,
notekey: "",
note: undefined
});
}
exports.save = function(req, res, next) {
if (req.body.docreate === 'create') {
notes.create(req.body.notekey,
req.body.title,
req.body.body);
} else {
notes.update(req.body.notekey,
req.body.title,
req.body.body);
}
res.redirect('/noteview?key='+req.body.notekey);
}
please help me in my problem, thank you for your help.
Thank again.
I think you should use 'body-parser'. Please Read this
In this part of the code:
exports.save = function(req, res, next) {
if (req.body.docreate === 'create') {
notes.create(req.body.notekey,
req.body.title,
req.body.body);
} else {
notes.update(req.body.notekey,
req.body.title,
req.body.body);
}
res.redirect('/noteview?key='+req.body.notekey);
}
You are trying to get the property docreate of req.body and the error is saying that that property doesn't exist. Make sure it is defined before checking if it is equal to 'create'

TypeError: data is not iterable

I'm trying out Node.js and sqlite database work and have come across this and I am currently stuck.
my console error is:
TypeError: data is not iterable
at db.all (C:\Users\Taylor\Desktop\book\index1.js:30:22)
at Statement.errBack (C:\Users\Taylor\node_modules\sqlite3\lib\sqlite3.js:16:21)
--> in Database#all('SELECT id, title FROM Jobs;', [Function])
at app.get (C:\Users\Taylor\Desktop\book\index1.js:26:6)
at Layer.handle [as handle_request] (C:\Users\Taylor\Desktop\book\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Taylor\Desktop\book\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\Taylor\Desktop\book\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\Taylor\Desktop\book\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Taylor\Desktop\book\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\Taylor\Desktop\book\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\Taylor\Desktop\book\node_modules\express\lib\router\index.js:275:10)
at urlencodedParser (C:\Users\Taylor\Desktop\book\node_modules\body-parser\lib\types\urlencoded.js:91:7)
this is my js script:
app.get('/', async(req, res) => {
const sql = 'SELECT id, title FROM Jobs;'
console.log(sql)
db.all(sql, (err, data) => {
if(err) console.error(err.message)
console.log(data)
let list = '<ol>'
for(const job of data) {
console.log(job.title)
list += `<li>${job.title}</li>`
}
list += '</ol>'
console.log(list)
res.render('index', {locals: {Jobs: list}})
})
})

insomnia -- Cannot read property 'post' of undefined

var express = require('express');
var path = require('path');
var app = express();
var mongoose = require('mongoose');
var bodyparser = require('body-parser');
mongoose.Promise = require('bluebird');
mongoose.connect("mongodb://makja:q1w2e3r4#ds111123.mlab.com:11123/makja" , { useMongoClient: true });
var db = mongoose.connection;
db.once("open", function () {
console.log("DB on!");
});
db.on("error", function (err) {
console.log("DB error : " , err);
});
var dataSchema = mongoose.Schema({
name:String,
count:Number
});
var postSchema = mongoose.Schema({
title : {type:String, required:true},
body : {type:String, required:true},
createdAt : {type:Date, default:Date.now},
updatedAt : Date
});
var Post = mongoose.model('post',postSchema);
app.get('/posts', function(req , res){
Post.find({}, function(err,posts){
if (err) return res.json({success:false, message:err});
res.json({success:true, data:posts});
});
});
app.post('/posts', function(req , res){
Post.create(req.body.post, function(err,post){
if (err) return res.json({success:false, message:err});
res.json({success:true, data:post});
});
});
var Data = mongoose.model('data',dataSchema);
Data.findOne({name:"myData"},function(err,data){
if (err) return console.log("Data error",err);
if (!data) {
Data.create({name:"myData",count:0},function(err,data){
if (err) return console.log("Data error:",err);
console.log("counter initalized:",data);
});
}
});
app.set("view engine",'ejs');
app.use(express.static(path.join(__dirname,'public')));
app.use(bodyparser.json());
app.get('/',function(req , res) {
Data.findOne({name:"myData"}, function(err,data){
if(err) return console.log("Data error: ",err);
data.count++;
data.save(function(err){
if(err) return console.log("Data error: ",err);
res.render('my_first_ejs',data);
});
});
});
app.get('/',function (req,res) {
res.render('my_first_ejs');
});
app.listen(8000, function(){`enter code here`
console.log('Server On!');
});
cmd error -------------------------------
TypeError: Cannot read property 'post' of undefined
at C:\nodejs\index.js:38:23
at Layer.handle [as handle_request] (C:\nodejs\node_modules\express\lib\router\layer.js:95:5)
at next (C:\nodejs\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\nodejs\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\nodejs\node_modules\express\lib\router\layer.js:95:5)
at C:\nodejs\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\nodejs\node_modules\express\lib\router\index.js:335:12)
at next (C:\nodejs\node_modules\express\lib\router\index.js:275:10)
at expressInit (C:\nodejs\node_modules\express\lib\middleware\init.js:40:5)
at Layer.handle [as handle_request] (C:\nodejs\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\nodejs\node_modules\express\lib\router\index.js:317:13)
at C:\nodejs\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\nodejs\node_modules\express\lib\router\index.js:335:12)
at next (C:\nodejs\node_modules\express\lib\router\index.js:275:10)
at query (C:\nodejs\node_modules\express\lib\middleware\query.js:44:5)
at Layer.handle [as handle_request] (C:\nodejs\node_modules\express\lib\router\layer.js:95:5)
make sure your bodyparser is actually parsing body and attaching body to req before your POST is getting handled.
--> app.use(bodyparser.json());
var app = require('express')();
var bodyParser = require('body-parser');
app.post('/', (req, res) =>{
console.log(req.body); //undefined
res.json(req.body).status(200);
})
app.use(bodyParser.json());
app.listen(3000);
====
var app = require('express')();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/', (req, res) =>{
console.log(req.body); //attaches correctly
res.json(req.body).status(200);
})
app.listen(3000);