Req.body is empty and also cannot read property path of undefined - node.js

My project was working fine till last week and now all of a sudden my post requests are not working . i tried all methods and read other questions of stack overflow but was unable to fix the issue . can some one please help me?
Issue : req.body is undefined and also whenever i try upload a file "cannot read property path of undefined" is the error.
i'm using express middle ware to parse the request body . i also have my form enctype to multipart/form-data..
Code snippet is below :
require('dotenv').config()
const express = require('express');
const app = express();
const router = express.Router();
const session = require('express-session');
const fs = require(`fs`);
const mysql = require(`mysql-await`);
const path = require('path');
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
const multer = require('multer');
const {storage} = require('../cloudinary');
const upload = multer({storage});
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "Sujanya#1978",
database: "dept"
});
con.connect((err) => {
if (!err) {
console.log("Connected");
}
else {
console.log(err)
}
})
router.get('/naaccircular',(req,res)=>{
(async () => {
let results = await con.awaitQuery('select* from dept.naaccircular;');
res.render('Naac_circular',{Egs : results})
})();
})
router.get('/naaccriteria',(req,res)=>{
(async () => {
flet results = await con.awaitQuery('select* from dept.naaccriteria;');
res.render('Naac_criteria_files',{Fgs : results})
})();
})
router.post('/naacaddcircular',upload.single('circularfile'),(req,res) => {
console.log(req.body);
const n = req.body.circularname;
const d = req.body.circulardate;
const l = req.file.path;
con.connect(function(err){
var records = [n,d,l];
con.query("insert into dept.naaccircular (cirname,cirlink,cirdate)
VALUES (?,?,?)", [n,l,d] , function (err, result, fields){
if (err) throw err;
})
});
console.log(n);
console.log(l);
console.log(d);
res.redirect('/naaccircular');
})
module.exports = router;
style="margin-top:80px; background-color: white;">
<form action="/naacaddcircular" method="POST" class="row g-3 form-container" enctype="multipart/form-data">
<h3 style="text-align: center;">Naac Circular</h3>
<div class="mb-3">
<label for="ii" class="form-label">Name</label>
<input id="ii" name="circularname" class="form-control" type="text" placeholder="Default input"
aria-label="default input example">
</div>
<div class="mb-3">
<label for="jj" class="form-label">Date</label>
<input id="jj" name="circulardate" class="form-control" type="date">
</div>
<div class="input-group mb-2">
<input type="file" class="form-control" name="circularfile"id="inputGroupFile04" aria-describedby="inputGroupFileAddon04"
aria-label="Upload">
<!--<button class="btn btn-outline-secondary" type="button" id="inputGroupFileAddon04">Button</button>-->
</div>
<button type="submit"
class="btn btn-primary position-relative start-50 botttom-0 translate-middle-x">Upload</button>
</form>
</div> ```

The problem is with cloudinary module. I have rectified it, there are no errors in the post method.
Once upload.single() function is removed from the router.post() function I'm able to get the req.body(),

Related

Can't redirect after Mongoose query

I am trying to create a website with user accounts.
But can't redirect after Mongoose save query in register page.
Here is NodeJS index.js file
const express = require('express')
const app = express();
const cors = require('cors');
const mongoose = require('mongoose');
const CryptoJS = require('crypto-js');
const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');
const User = require('./models/User');
dotenv.config();
app.set('view engine', 'ejs');
app.use(cors());
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use(express.static('public'));
app.use(express.static('partials'));
app.use(express.static('images'));
app.use(express.static('assets'));
mongoose.connect(process.env.MONGO_URL)
.then(() => {
console.log('DB is connected');
})
.catch((err) => {
console.log(err);
});
app.post('/register', async (req, res) => {
const newUser = new User({
email: req.body.email,
password: CryptoJS.AES.encrypt(req.body.password, process.env.PASS_SEC).toString()
})
try {
const savedUser = await newUser.save();
res.redirect('/')
} catch (err) {
console.log(err)
}
})
(of course app.get('/') and app.get('/login') exists in my index.js file)
My register page (register.ejs)
<%- include('./partials/header') %>
<div class='container'>
<div class="login">
<h1 class='heading'>Register</h1>
<div class='form-block'>
<form action="/register" method="POST">
<label class='label'>Email</label>
<input class='input' type='email' name='email' placeholder='example#mail.com' required/>
<label class='label'>Password</label>
<input class='input' type='password' name='password' placeholder='********' required/>
<input class='button' type='submit' value='Sign Up' />
</form>
</div>
</div>
</div>
<%- include('./partials/footer') %>
Instead of redirect to main page I get json data of saved User.
How to fix that?

Body parser returning undefined for req.body request (SIMPLE LOGIN for beginner)

So I installed body parser via
npm i install express body-parser
and I wrote a simple code designed to input a user into an array after they complete a registration form.
but when I console.log the user it returns undefined for both email and password
here is the server code
const express = require('express');
const path = require('path');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const PORT = 3000;
var Users = [{"email":"mike#gmail.com", "password":"456"}];
app.get('/', (req, res) => {
res.render('index.ejs')
})
app.get('/Register.ejs', (req, res) => {
res.render('Register.ejs')
})
app.post('/views/Register.ejs', (req, res) =>
{
const newUser = {
email: req.body.email,
password: req.body.password
};
Users.push(newUser);
res.json(req.body.email);
console.log(Users)
}
)
app.listen(PORT);
here is the html for the register page
<h1>Please Register</h1>
<body>
<form action="/views/Register.ejs" method="POST">
<div class="div">
<label for="email">Enter Email</label>
<input type="email" id="email"for="email" id="email" required>
</div>
<div class="div">
<label for="password">Enter new password</label>
<input type="password" for="password" id="password" required>
</div>
<button type="submit"> Register </button>
</form>
</body>
Only installing body-parser is not enough. You have to put them in the code as middleware.
Top of the code use:
var bodyParser = require('body-parser');
and then use the code in somewhere middle of the code:
app.use(bodyParser.json())

How to move from one route to other in node.js

I have form post job.html and a button post. I want that when someone submits this form the values save in database and then i get these values on another helper's feed.html page. Right now, my values are saving in database but i am unable to understand how to get those values in next page.
This is the part of html code for helpers feed.
<div class="col-md-10" >
<div> Description:
<input type="text" id="desc" name="budget"class="form-control">
<div>
<div> Category:
<input type="text" id="category" name="budget" class="form-control">
</div>
<div > City:
<input type="text" id="city" name="budget" class="form-control">
</div>
<div > Budget
<input type="text" id="budget" name="budget" class="form-control">
</div>
This is node.js file. post.js
var mysql = require('mysql');
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'sahoolat1',
database : 'fyp_sahoolat'
});
connection.connect(function(err){
if(err) throw err;
console.log("connected");
});
var app = express();
app.use(bodyParser.urlencoded({extended : false}));
app.use(bodyParser.json());
app.get('/', function(request, response) {
response.sendFile(path.join(__dirname + '/job post.html'));
});
app.post('/post',(request,response,next)=>{
var description=request.body.description;
var contact_number=request.body.contact_number;
var city=request.body.city;
var budget=request.body.budget;
var category=request.body.optradio;
var query=connection.query("insert into jobs(Jobs_id,Description,Category,City,Contact_number,Budget) values(?,?,?,?,?,?)",[null,description,category,city,contact_number,budget],function(err){
if(err)
console.log(err);
else
console.log("moving");
});
next();
});
app.get('/post',(request, response) => {
connection.query("SELECT * FROM jobs",(err, result) => {
if(err) {
console.log(err);
}
else {
console.log(result);
res.send(result);
}
});
});
app.listen(3000);
The code runs fine till the line where i am saving in database and it prints "moving" on console.
I want to get each field value in the respective text fiels(as shown in screenshot)

Express - POST request pending

I have a form to register users, but post request is not working
I've checked bodyparser, consign includes order, added enctype to form and still do not work
The route is working, cause it calls my controller, but as you can see at console image, it goes to the controller with undefined req, althought url params are defined at devtools
server.js:
const express = require('express');
const consign = require('consign');
const bodyParser = require('body-parser');
const expressValidator = require('express-validator');
const helmet = require('helmet');
const jwt = require('jsonwebtoken');
require('dotenv-safe').load();
const app = express();
app.set('view engine', 'ejs');
app.set('views', './app/paginas');
app.use(express.static('./app/publico/'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(expressValidator());
consign(/* {cwd: 'app'} */)
.include('config/conectarBD.js')
.then('app/modelos')
.then('app/controles')
.then('app/rotas')
.into(app);
/* consign()
.include('app/rotas')
.then('config/conectarBD.js')
.then('app/modelos')
.then('app/controles')
.into(app); */
console.log('Instância do app criada');
module.exports = app;
form.ejs:
<div class="row" id="form_registro">
<div class="col-sm-6 offset-sm-3 text-center">
<form action="/registrar" method="POST">
<fieldset>
<legend>Registro</legend>
<div class="form-group">
<label for="form-r-email">Nome:</label>
<input type="text" class="form-control" id="nome" name="nome" placeholder="Seu nome">
</div>
<div class="form-group">
<label for="form-r-email">Email:</label>
<input type="email" class="form-control" id="email" name="email"
placeholder="Seu email">
</div>
<div class="form-group">
<label for="form-r-senha">Senha:</label>
<input type="password" class="form-control" id="senha" name="senha"
placeholder="Sua senha">
</div>
<!-- TODO implementar -->
<div class="form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck2">
<label class="form-check-label" for="exampleCheck1">Lembre de mim</label>
</div>
<button type="submit" class="btn btn-success">Registrar</button>
</fieldset>
<div>
Já tem uma conta?
Registrar!
</div>
</form>
</div>
</div>
route login.js:
module.exports = function(application) {
application.get('/login', function(req, res) {
console.log('Rota pegaPaginaLogin');
application.app.controles.login.pegaPaginaLogin(application, req, res);
});
application.post('/admin/logar', function(req, res) {
console.log('Rota /admin/logar');
application.app.controles.login.logaUsuario(application, req, res);
});
application.post('/registrar', function(req, res) {
console.log('Rota registrar');
console.log('req.body >>>' + req.body);
res.status(500).send('testing');
application.app.controles.login.registraUsuario(application, req, res);
});
}
controller registraUsuario:
module.exports.registraUsuario = function (application, req, res) {
console.log('Controller registraUsuario');
console.log('REQ....' + req)
var usuario = req.body;
/** Validação do formulário */
//TODO validar formatos
req.assert('nome', 'Nome é obrigatório').notEmpty();
req.assert('email', 'Email é obrigatório').notEmpty();
req.assert('senha', 'Senha é obrigatório').notEmpty();
var errosValidacao = req.validationErrors();
console.log(errosValidacao);
if (errosValidacao) {
res.render('login', {
validacao: errosValidacao,
usuario: usuario
});
return;
}
/** Conexão com banco */
var conexao = application.config.conectarBD();
var novoUsuario = new application.app.modelos.UsuariosModel(conexao);
novoUsuario.getUsuario(usuario, function (error, result) {
console.log(result);
novoUsuario.novoUsuario(usuario);
});
}
model UsuariosModel:
function UsuariosModel(conexao) {
this._conexao = conexao;
}
/** Se usuário existir, retorna a id_usuario */
UsuariosModel.prototype.getUsuario = function (usuario, callback) {
console.log('Model getUsuario');
this._conexao.query('SELECT id_usuario FROM usuarios WHERE email = "' + usuario.email + ' and senha = "' + usuario.senha + '"');
}
UsuariosModel.prototype.novoUsuario = function (usuario, callback) {
var hoje = Date.now();
this._conexao.query('INSERT INTO usuarios SET ?', usuario, callback);
}
module.exports = function () {
return UsuariosModel;
};
console:
error:
Your server code is not calling response.send.
Replace your code with this to test:
application.post('/registrar', function(req, res) {
console.log('Rota registrar');
console.log('REQ.query....' + req.params.name);
res.status(500).send('testing');
//application.app.controles.login.registraUsuario(application, req, res);
});
In registraUsuario, you need to call send with your response/status code. Yourclient will block until send is called, or a timeout occurs.

Not getting data in post form

i've been trying to get the data in a form with the POST method, but i don't get any, i've been reading a book to learn about expressjs.. this is my form:
<form method="post">
<div class="form-group">
<label for="usernameInput" class="col-md-2">Username</label>
<div class="col-md-12">
<input type="text" class="form-control" id="usernameInput" name="username" placeholder="Enter username">
</div>
</div>
<div class="form-group">
<label for="passwordInput" class="col-md-2">Password</label>
<div class="col-md-12">
<input type="password" class="form-control" id="passwordInput" name="password" placeholder="Enter password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-11">
<div class="checkbox">
<label>
<input type="checkbox"> Remember me
</label>
</div>
</div>
</div>
<button type="submit" class="btn btn-default">Log in</button>
</form>
and this is my node code.
/*
Chat application for #node.js
express version.
*/
//Load modules.
var express = require('express'),
http = require('http'),
socket = require('socket.io'),
swig = require('swig'),
fs = require('fs');
//Load config.
console.log('Loading configuration.');
var config = fs.readFileSync('config.json');
var config = JSON.parse(config);
var port = config.port;
var views = config.views;
console.log('Configuration loaded.');
//Initiate express module in app.
var app = express();
//Global vars
var Title = "Node.js Chat";
var result = '';
app.engine('html', swig.renderFile);
//Set view engine.
app.set('view engine', 'html');
//Set the directory for views.
app.set('views', __dirname + '/views');
swig.setDefaults(
{
cache: false
});
app.get('/', function(request, response)
{
console.log('GET OK');
response.render('index',
{
'Title': Title,
'result': result,
});
});
app.post('/', function(request, response)
{
console.log('POST OK');
console.log(request.body);
response.render('index',
{
'Title': Title,
'result': 'Post detected.',
});
});
//logger.
app.use(function(request, response, next)
{
console.log('%s %s', request.method, request.url);
var file = request.url.slice(1 + request.url.indexOf('/'));
app.get(request.url, function(request, response)
{
response.render(file,
{
//Var to be named in the render : value;
'Title': Title,
'result': result,
});
});
next();
});
//Set directory for static files (css, js, img)
app.use(express.static(__dirname + '/public'));
//Run the app.
http.createServer(app).listen(port, function()
{
console.log('Server listening to ' + port);
});
i get "undefined" in request.body, which i dont know why i get this error, i've tried with other methods like request.param, or request.query, but they get nothing, i've made sure the post is detected and its why it sends the message that's being detected, but i want to get the data in the form..
You need the now-separate body-parser middleware. Run npm install body-parser or add body-parser to your package.json and npm install it.
Add var bodyParser = require('body-parser'); to your module-loading, then after instantiating your app, add the middleware with app.use(bodyParser());. That will populate req.body for the form.
add in app.js:
app.use(express.bodyParser());
As the comment indicated, it depends on the express version.
It works with 3.x as stated above.
For 4.0, you must manually include these frameworks that were previously included. See the note from vision media (overview tab):
https://github.com/visionmedia/express/wiki/Migrating-from-3.x-to-4.x
These are NOT included to allow independent updates

Resources