user4489673
user4489673

Reputation:

Input value "undefined" Node.js

I have some trouble with nodejs and express, I'm actually trying to get the value of inputs from a view "inscription.ejs" but when I question the object "req" he return null values.

The structure of the project :

In server.js i just make a call of routes.js in order to load the routes with this lines :

require('./config/routes')(app)

In routes.js I make different calls in the controller folder and actually everything work :

var user = require('../app/controller/user');
var book = require('../app/controller/book');
var home = require('../app/controller/home');

/**
 * Expose
 */

module.exports = function (app) {
    app.get('/home', home.index)
    app.get('/home/inscription', home.inscription)
    app.post('/home/inscription', user.addUser)
}

Here the problem, in user.js :

var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var models = require('../entity/modele')(mongoose);

exports.addUser = function(req, res){
    console.log(req.params);
    res.render('user');
};

When i send the form, I'm redirect in the template "user.ejs" but in the console the value of inputs are undefined. I tried to use :

req.body.name
req.param(name)

No result.

Upvotes: 0

Views: 1801

Answers (2)

Eder Ramos
Eder Ramos

Reputation: 1

Take in consideration that if you are passing the information through the URL, you will use params, however if your are passing the information using JSON, you will use req.body when you will destructure it instead of req.params.

Upvotes: 0

HDK
HDK

Reputation: 814

check configuration of body-parser middleware in server.js file

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded 
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json 
app.use(bodyParser.json())

app.use(function (req, res) {
  res.setHeader('Content-Type', 'text/plain')
  res.write('you posted:\n')
  res.end(JSON.stringify(req.body, null, 2))
})
 // your route configuration here 

Upvotes: 0

Related Questions