Handling POST submission - node.js

Looks like a simple task, but I can not find out the error in my code.
app.js
var http = require('http');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var routes = require('./routes')(app);
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.set('view engine', 'jade');
app.set('views', './views');
app.use(express.static('./public'));
app.listen(3000, function() {
console.log('hello');
console.log('express server listening on port:' + 3000);
});
index.jade
html
head
title Welcome
body
p Enter your name and email address to become a member.
form(action='/signup', method='post')
div
label Name
input(type='text', name='name')
div
label Email
input(type='text', name='email')
div
input(type='submit')
routes.js
module.exports = function(app) {
app.get('/', function(req, res) {
res.render('index');
});
app.post('/signup', function(req, res) {
console.log(req);
console.log(req.body);
var name = req.body.name;
var email = req.body.email;
console.log('Name: ' + name);
console.log('Email: ' + email);
res.json(req.body);
});
};
When I post the form I get the error:
TypeError: Cannot read property 'name' of undefined
at /Users/demas/temporary/express/1/routes.js:11:22
at Layer.handle [as handle_request] (/Users/demas/temporary/express/1/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/demas/temporary/express/1/node_modules/express/lib/router/route.js:131:13)
at Route.dispatch (/Users/demas/temporary/express/1/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/demas/temporary/express/1/node_modules/express/lib/router/layer.js:95:5)
at /Users/demas/temporary/express/1/node_modules/express/lib/router/index.js:277:22
at Function.process_params (/Users/demas/temporary/express/1/node_modules/express/lib/router/index.js:330:12)
at next (/Users/demas/temporary/express/1/node_modules/express/lib/router/index.js:271:10)
at expressInit (/Users/demas/temporary/express/1/node_modules/express/lib/middleware/init.js:33:5)
at Layer.handle [as handle_request] (/Users/demas/temporary/express/1/node_modules/express/lib/router/layer.js:95:5)
In the console I can see the req.body is undefined. Why?

You need to do your configuration before you do the routing, so moving down this line :
var routes = require('./routes')(app);
Below this :
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
... should work.

Related

req.checkBody is not a function with Express-Validator NODEJS

Hi I'm trying doing a login page, after clicking on submit I'm getting this error with express-validator version 5.3.1
req.checkBody is not a function
TypeError: req.checkBody is not a function
at Strategy._verify (C:\Users\aless\Desktop\js_cart-master\config\passport.js:67:7)
at Strategy.authenticate (C:\Users\aless\Desktop\js_cart-master\node_modules\passport-local\lib\strategy.js:90:12)
at attempt (C:\Users\aless\Desktop\js_cart-master\node_modules\passport\lib\middleware\authenticate.js:369:16)
at authenticate (C:\Users\aless\Desktop\js_cart-master\node_modules\passport\lib\middleware\authenticate.js:370:7)
at Layer.handle [as handle_request] (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:275:10)
at C:\Users\aless\Desktop\js_cart-master\routes\user.js:39:3
at Layer.handle [as handle_request] (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:317:13)
at C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:335:12)
In my app.js I have required express-validator with const validator = require('express-validator');//#5.3.1
and used it with app.use(validator());
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const mongoose = require('mongoose');
const passport =require('passport');
const flash = require('connect-flash');
const bcrypt = require('bcrypt');
const validator = require('express-validator');//#5.3.1
const session = require('express-session');
const MongoStore = require('connect-mongo');
const env = require('dotenv').config()
const app = express();
mongoose.connect(process.env.URI,{ useNewUrlParser: true });
require('./config/passport');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(validator());
app.use(cookieParser());
app.use(session({
secret: "key per i cookie",
saveUninitialized: false,
resave: false,
store: MongoStore.create({
mongoUrl: process.env.URI,
autoRemove: 'disabled'
}),
cookie: { maxAge:30000,secure:false }
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
//verify if authenticated
app.use((req, res, next)=>{
res.locals.login =req.isAuthenticated();
//access sessions through templates
res.locals.session = req.session;
next();
});
//routes
app.use('/', require('./routes/index'));
app.use('/user', require('./routes/user'));
// 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;
Using this express-validator version I got this error when submit, using last express-validator version I get same error in console.
Why I'm getting this error??
The reason is the way you are requiring it.
const { body, validationResult } = require('express-validator');
In your code you can make these changes and try:
const { validationResult } = require('express-validator');//#5.3.1
.
.
.
app.use(validationResult());
Note: check this link for more information.

SyntaxError: Unexpected token ,while compiling ejs

I just started to learn Node JS. While rendering the ejs file, I got an Unexpected token error. Anyone help me out for this error. My code is below:
ERROR:
SyntaxError: Unexpected token { in C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\views\blogpost.ejs while compiling ejs
If the above error is not helpful, you may want to try EJS-Lint:
https://github.com/RyanZim/EJS-Lint
Or, if you meant to create an async function, pass async: true as an option.
at new Function (<anonymous>)
at Template.compile (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\ejs\lib\ejs.js:633:12)
at Object.compile (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\ejs\lib\ejs.js:392:16)
at handleCache (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\ejs\lib\ejs.js:215:18)
at tryHandleCache (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\ejs\lib\ejs.js:254:16)
at View.exports.renderFile [as engine] (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\ejs\lib\ejs.js:485:10)
at View.render (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\express\lib\view.js:135:8)
at tryRender (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\express\lib\application.js:640:10)
at Function.render (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\express\lib\response.js:1012:7)
app.js
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.send('Blog Homepage.');
});
app.get('/posts', function(req, res) {
res.render('blogpost.ejs', {posts : "posts"});
});
app.listen(3000, function() {
console.log("Server is started.");
});
blogpost.ejs
<h1>Blog <%= posts %> </h1>
Thanks in advance.
I just update your code, seem you're forgot set view engine
var express = require('express');
var app = express();
var path = require('path');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.send('Blog Homepage.');
});
app.get('/posts', function(req, res) {
res.render('blogpost.ejs', {posts : "posts"});
});
app.listen(3000, function() {
console.log("Server is started.");
});
Please make sure you run npm i ejs.
And you may need store all your view files in a folder for more clearly folder struct. In this code, please move your blogpost.ejs to views folder. Hope this helpfull
const express = require('express');
const path = require('path');
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/', (req, res)=>{
res.render('homepage');
});
app.get('blog', (req, res)=>{
let post = req.query.post;
res.render('blog', {post: post});
});
let port = 4444;
app.listen(port, ()=>{
console.log(`server has started on port: ${port}`);
});

How to export function from app.js and import it from another js-file?

I'm setting up a new server with node js and the framework express (Version 4.16). I want to route my Rest-Endpoints. In my route.js-file i want to call a function from app.js(my Server), but getting a Typeerror where the function, that i want to call from another file, is not a function.
Error:
TypeError: callFunction.getDataFromDb is not a function
at C:\Users\---\WebstormProjects\pwa_node_server\routes\recipes.js:7:18
at Layer.handle [as handle_request] (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\index.js:47:12)
My server:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var axios = require('axios');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var recipesRouter = require('./routes/recipes');
var cors = require('cors');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors({credentials: true, origin: true}));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/recipes', recipesRouter);
// app.use('/poste-dein-rezept', indexRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
console.log("catch404");
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');
});
var getDataFromDb = function (res) { // This function to call in another file
};
module.export = {
getDataFromDb
};
module.exports = app;
My route-file:
var express = require('express');
========
var router = express.Router();
var callFunction = require('../app');
router.get('/', function(req, res, next) {
console.log('Recipes-Endpoint received Request');
callFunction.getDataFromDb(res);
});
module.exports = router;
I just want to call a function from another file.
You're using module.export. The Correct property name is module.exports, which you are also using.
One way to solve this is:
app.getDataFromDb = getDataFromDb;
module.exports = app;

"no default engine" error when running MEAN application

Error: Failed to lookup view "error" in views directory "/var/www/html/mean/mean-secure1/views"
at Function.render (/var/www/html/mean/mean-secure1/node_modules/express/lib/application.js:581:17)
at ServerResponse.render (/var/www/html/mean/mean-secure1/node_modules/express/lib/response.js:1008:7)
at /var/www/html/mean/mean-secure1/app.js:50:7
at Layer.handle_error (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/layer.js:71:5)
at trim_prefix (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:315:13)
at /var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:335:12)
at next (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:275:10)
at /var/www/html/mean/mean-secure1/app.js:39:3
at Layer.handle [as handle_request] (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:317:13)
at /var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:335:12)
at next (/var/www/html/mean/mean-secure1/node_modules/express/lib/router/index.js:275:10)
at SendStream.error (/var/www/html/mean/mean-secure1/node_modules/serve-static/index.js:121:7)
at SendStream.emit (events.js:182:13)
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var config = require('./config/database');
var api = require('./routes/api');
var app = express();
//app.set('view engine', 'pug');
mongoose.Promise = require('bluebird');
mongoose.connect(config.database, { promiseLibrary: require('bluebird') })
.then(() => console.log('connection succesful'))
.catch((err) => console.error(err));
app.use(passport.initialize());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended':'false'}));
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/books', express.static(path.join(__dirname, 'dist')));
app.use('/api', api);
//app.use(express.static(path.join(_dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
// 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');
});
module.exports = app;
If you want to use ejs templating as your view engine then you can use below code to set the view engine for your node application
const ejs=require("ejs");
app.set('view engine','ejs');

TypeError: Cannot read property 'buffer' of undefined

My code:
var express = require("express");
var bodyParser = require("body-parser");
var multer = require("multer");
var fs = require("fs");
var ejs = require('ejs');
var app = express();
var upload = multer({ dest: 'uploads/' })
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/', function(req, res){
console.log('Works');
res.render('index');
});
app.post('/', upload.single('test'), function (req, res, next) {
var raw = new Buffer(req.file.buffer.toString(), 'base64');
fs.writeFile('./uploads/upload.png', raw, function (err) {
if (err) {
console.log('Error');
return next(err);
}
res.end('Success!');
});
});
var server = app.listen(3000, function() {
console.log("Listening on port %s...", server.address().port);});
My error:
TypeError: Cannot read property 'buffer' of undefined
at /Users/jacob/nodejs-prj/polyglotdev-test/app.js:27:33
at Layer.handle [as handle_request] (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/route.js:137:13)
at multerMiddleware (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/multer/lib/make-middleware.js:18:41)
at Layer.handle [as handle_request] (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/layer.js:95:5)
at /Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/index.js:335:12)
I have to receive image file as base64 format from rasperry pi. Then i have to decode it back to image and save it in mongo db.
I was trying to send some test data with postman to my endpoint. But always this error occurs.
In Postman it looks likes this:
Screenshot of postman
Try this:
var upload = multer({
dest: 'uploads/',
storage: multer.memoryStorage()
});
I solved this problem. Forget about my 'index.ejs' file, there's a tag ''. Attribute 'name="test"' must be equal to argument in "upload.single('test')".

Resources