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'
Related
Stuck on this error Please help cannot move forward.....
I am studying on udemy of complete beginners course by dr angela vu . my code is same as Dr angela but still getting this error.
stuck on section 28-347 Udemy
Dr. Angela Yu web course
Getting error as under.
thanks in advance
by M S Jhala
TypeError: D:\B_study\WebDevelopment\Project_web\toDoLIstMongo\views\list.ejs:10
8|
9|
>> 10| <% newListItems.forEach(function(item){ %>
11| <form action="/delete" method="post">
12| <div class="item" >
13| <input type="checkbox" name="checkbox" value= "<%=item._id%>" onChange="this.form.submit()" >
Cannot read properties of undefined (reading 'forEach')
at eval ("D:\\B_study\\WebDevelopment\\Project_web\\toDoLIstMongo\\views\\list.ejs":16:21)
at list (D:\B_study\WebDevelopment\Project_web\toDoLIstMongo\node_modules\ejs\lib\ejs.js:703:17)
at tryHandleCache (D:\B_study\WebDevelopment\Project_web\toDoLIstMongo\node_modules\ejs\lib\ejs.js:274:36)
at View.exports.renderFile [as engine] (D:\B_study\WebDevelopment\Project_web\toDoLIstMongo\node_modules\ejs\lib\ejs.js:491:10)
at View.render (D:\B_study\WebDevelopment\Project_web\toDoLIstMongo\node_modules\express\lib\view.js:135:8)
at tryRender (D:\B_study\WebDevelopment\Project_web\toDoLIstMongo\node_modules\express\lib\application.js:657:10)
at Function.render (D:\B_study\WebDevelopment\Project_web\toDoLIstMongo\node_modules\express\lib\application.js:609:3)
at ServerResponse.render (D:\B_study\WebDevelopment\Project_web\toDoLIstMongo\node_modules\express\lib\response.js:1039:7)
at D:\B_study\WebDevelopment\Project_web\toDoLIstMongo\toDoApp.js:73:19
at D:\B_study\WebDevelopment\Project_web\toDoLIstMongo\node_modules\mongoose\lib\model.js:5095:18
list.ejs
<%- include("header") -%>
<div class="box" id="heading">
<h1> <%= listTitle %> .</h1>
</div>
<div class="box">
<% newListItems.forEach(function(item){ %>
<form action="/delete" method="post">
<div class="item" >
<input type="checkbox" name="checkbox" value= "<%=item._id%>" onChange="this.form.submit()" >
<p><%=item.name%></p>
</div>
<input type="hidden" name="listName" value="<%= listTitle %>"></input>
</form>
<% });%>
<form class="item" action="/" method="post">
<input type="text" name="newItem" placeholder="New Item" autocomplete="off">
<button type="submit" name="list" value= "<%= listTitle %>">+</button>
</form>
</div>
<%- include("footer") -%>
app.js
//jshint esversion:6
const express = require("express");
const bodyParser = require("body-parser");
const date = require(__dirname + "/date.js");
const app = express();
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
//mongoose
const mongoose =require("mongoose");
mongoose.connect('mongodb://localhost:27017/todoDB', { useNewUrlParser: true });
const itemsSchema ={
name:String
};
const Item = mongoose.model("Item",itemsSchema);
const item1 = new Item({
name:"Welcome to You To Do List."
});
const item2 = new Item({
name:"Hit the + button to add new item."
});
const item3 = new Item({
name:"<--- Hit this to delete item"
});
const defaultItems = [item1, item2, item3];
const listSchema = {
name:String,
item:[itemsSchema]
};
const List = mongoose.model("List",listSchema);
app.get("/", function(req, res) { // get This req when come from browser port 3000
Item.find({},function (err, foundItems) {
if (foundItems.length === 0){
Item.insertMany(defaultItems,function (err) {
if (err){console.log(err);} else {console.log("Sucessfully saved default items.");}
});
res.render("/");
}else {
res.render("list", { // rendering list.ejs with data in html
listTitle: "Today",
newListItems: foundItems
});
}
});
});
app.get("/:coustomListName",function (req,res) {
let coustomListName = req.params.coustomListName;
List.findOne({name:coustomListName},function (err, foundItems) {
if (!err){
if (!foundItems){
//creat new list
const list = new List({
name:coustomListName,
item: defaultItems
});
list.save();
res.redirect("/" +coustomListName);
}else{
//if found display the list
res.render("list", { // rendering list.ejs with data in html
listTitle: foundItems.name,
newListItems: foundItems.items
});
}
}else{
console.log("CustomItemError:"+err);
}
});
});
//Routing refers to how an application’s endpoints (URIs) respond to client requests.
app.post("/", function(req, res) { // function routes the HTTP POST requests to the specified path with the specified callback functions.
let itemName = req.body.newItem; // store post req body information
const listName =req.body.list;
const item = new Item({
name:itemName
});
if(listName=== "Today"){
item.save();
res.redirect("/");
}else{
List.findOne({name:listName},function (err,foundList) {
foundList.items.push(item);
foundList.save();
res.redirect("/"+listName);
});
}
});
app.post("/delete",function (req, res) {
const checkedItemId = req.body.checkbox;
const listName = req.body.listName;
Item.findByIdAndRemove(checkedItemId, function(err) {
if (!err){
console.log("Sucessfully Removed item");
res.redirect("/");
}
});
});
app.get("/work", function(req, res) {
res.render("list", {
listTitle: "Work List",
newListItems: workItems
});
});
app.post("/work", function(req, res) {
let item = req.body.newItem;
workItems.push(item);
res.redirect("/work");
});
app.get("/about",function (req,res) {
res.render("about");
})
app.listen(3000, function(req, res) {
console.log("Server started on port 3000.");
});
After trying
<% if (newListItems !== undefined && newListItems.length > 0) { %>
<% }%>
Error
Home page loaded but default list items doesnt show up
Error come while adding items
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
I am developing a nodejs express application with MySQL and for the session, authentication, and authorization I am using the passport, I dont know why but when I create the account everything goes fine. User is being created.
But when I login, it returns an error message saying "Missing credentials".
I have already seen every other Stackoverflow question regarding this problem but I haven't found a solution.
app.js
const express = require("express");
const cors = require('cors');
const accountRoute = require("./routes/account");
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.set("view engine","ejs");
app.use(express.static(__dirname + '/views'));
app.use(accountRoute.app)
app.use(accountRoute.router);
app.get("/", (req,res) => {
res.render("index.ejs");
});
app.listen(8000, () => console.log(`Listening on port 8000...`));
Login and Register
const express = require('express');
const session = require('express-session');
const flash = require('express-flash');
const bcrypt = require('bcryptjs');
const passport = require('passport');
const config = require('../config');
const initalizePassport = require('../passport');
const user = require('../models/user').User;
const router = express.Router();
const app = express();
initalizePassport(passport, async (email) => {
return await user.findOne({ where: { "email": email } }) === email;
}, async (id) => {
return await user.findOne({ where: { "id": id } }) === id;
});
app.use(session({
secret: config.sessionPassword,
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
router.get('/login', (req, res) => {
res.render('login.ejs');
});
router.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
}));
router.get('/register', (req, res) => {
res.render('register.ejs');
});
router.post('/register', async (req, res) => {
try {
const hashedPassword = await bcrypt.hashSync(req.body.userpass, 10);
user.create({
"email": req.body.email,
"username": req.body.username,
"userpass": hashedPassword
});
res.redirect('/login');
} catch (error) {
res.redirect('/register');
}
});
router.get('/unregister', (req, res) => {
res.render('unregister.ejs');
});
router.post('/unregister', (req, res) => {
res.send(req.body);
});
module.exports.router = router;
module.exports.app = app;
passport.js
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcryptjs')
function initialize(passport, getUserByEmail, getUserById) {
const authenticateUser = async (email, userpass, done) => {
const user = getUserByEmail(email);
if (!user) {
return done(null, false, { message: 'No user with that email' })
}
try {
var correctPassword = false;
await bcrypt.compare(userpass, user.userpass, function (err, result) {
if (err) {
console.log(err);
}
else {
correctPassword = true;
console.log("passwords match!");
return;
}
});
if (correctPassword) {
return done(null, user)
} else {
return done(null, false, { message: 'Password incorrect' })
}
} catch (e) {
return done(e)
}
}
passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'userpass' }, authenticateUser))
passport.serializeUser((user, done) => done(null, user.id))
passport.deserializeUser((id, done) => {
return done(null, getUserById(id))
})
}
module.exports = initialize
Login.ejs
<h1>Login</h1>
<% if(messages.error) { %>
<%= messages.error %>
<% } %>
<form action="/login" method="post">
<input name="email" type="text" placeholder="email">
<input name="userpass" type="password" placeholder="userpass">
<input type="submit" value="submit">
</form>
Now it's throwing me this:
Error: Illegal arguments: string, undefined
at _async (C:\Users\datte\Desktop\auth\node_modules\bcryptjs\dist\bcrypt.js:286:46)
at C:\Users\datte\Desktop\auth\node_modules\bcryptjs\dist\bcrypt.js:307:17
at new Promise (<anonymous>)
at Object.bcrypt.compare (C:\Users\datte\Desktop\auth\node_modules\bcryptjs\dist\bcrypt.js:306:20)
at Strategy.authenticateUser [as _verify] (C:\Users\datte\Desktop\auth\passport.js:13:24)
at Strategy.authenticate (C:\Users\datte\Desktop\auth\node_modules\passport-local\lib\strategy.js:90:12)
at attempt (C:\Users\datte\Desktop\auth\node_modules\passport\lib\middleware\authenticate.js:366:16)
at authenticate (C:\Users\datte\Desktop\auth\node_modules\passport\lib\middleware\authenticate.js:367:7)
at Layer.handle [as handle_request] (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:317:13)
at C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:275:10)
Executing (default): SELECT `id`, `email`, `username`, `userpass`, `createdAt`, `updatedAt` FROM `Users` AS `User` WHERE `User`.`email` = 'myemail' LIMIT 1;
I am trying to create an form that allows a person to send me an email.
However, I am getting a 404 error, shown below.
The form itself is rendering, so what I have in index.js is working.
Do I need some additional code somewhere else or am I missing a few additional pieces of code.
I have nodemailer etc and all the necessary packages installed too.
I am very new to this and I would appreciate any help.
Thank you!
404 error
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.post('/contactus', function (req, res) {
var mailOpts, smtpTrans;
//Setup Nodemailer transport, I chose gmail. Create an application-specific password to avoid problems.
smtpTrans = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: "me#gmail.com",
pass: "xxxxxx"
}
});
//Mail options
mailOpts = {
from: req.body.name + req.body.email,
to: 'yyyyyyyyyy#gmail.com',
subject: req.body.email + ' --Msg from contactus-form',
text: "Name: " + req.body.name + "Email: " + req.body.email +
"Contact No: " + req.body.contactNo + "QUERY: " + req.body.message
};
smtpTrans.sendMail(mailOpts, function (error, response) {
//Alert on event of message sent succeeds or fail.
if (error) {
res.render('contactus',{msg : 'Error occured, message not sent.', err : true});
}
else {
res.render('contactus',{msg : 'Message sent! Thank you.', err : false});
}
smtpTrans.close();
});
});
// 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;
contactus.hbs
<html>
<head>
<title></title>
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<div class="content">
<form action="/contactus" method="post">
<fieldset>
<p>
<input type="text" name="name" size="30" required="" placeholder="Name:">
</p>
<p>
<input type="text" name="contactNo" size="30" placeholder="Contact No.:">
</p>
<p>
<input type="text" name="email" size="30" required="" placeholder="Email:">
</p>
<p><br>
<textarea type="text" name="message" cols="37" rows="7" size="30" placeholder="Your message please"></textarea>
</p>
<p>
<input name="submit" type="submit" value="Send" id="submit">
</p><br>
</fieldset>
</form>
</div>
</body>
</html>
This handler:
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
Should be moved to just before the 500 error handler.
The reason, it acts as a catch all. Meaning it will always execute if something before it did not route some place first. So it runs and sends the 404 before it has a chance to get to the contactus route.
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);