Reputation: 9
html form
<form method="post" action="/login">
<input type="text" name="user_vi" placeholder="User name vi" value="usernametest">
<input type="text" name="email_vi" placeholder="Email vi">
<br/>
<input type="text" name="user_en" placeholder="User name en">
<input type="text" name="email_en" placeholder="Email en">
<input type="submit" value="Submit">
</form>
app.js
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.set('views', './views'); // specify the views directory
app.set('view engine', 'ejs'); // register the template engine
app.get('/', function(req, res) {
res.render('index', { title: 'Home page', message: 'Home there!' })
});
app.get('/login', function(req, res) {
res.render('login', { title: 'Login', message: 'Login there!' })
});
app.post('/login', function(req, res) {
var lang = 'vi';
var user_name = 'user_' + lang;
//console.log(user_name);
//result = "user_vi"
console.log(req.body.user_name);
//result = undefined
console.log(req.body.user_vi);
//result = 'usernametest'
res.render('login', {
title: 'Login',
message: 'Login there!'
});
});
app.listen(3000, function() {
console.log('connect port 3000');
});
var lang = 'vi';
var user_name = 'user_' + lang;
//console.log(user_name);
//result = "user_vi"
//console.log(req.body.user_vi);
//result = 'usernametest'
console.log(req.body.user_name);
//result = undefined
I cannot get value here (req.body.user_name). How can I get this ?
Upvotes: 0
Views: 7577
Reputation: 598
req.body is an object. you are accessing the key wrongly.
your body object will look like this.
body{
"user_vi":"value",
"email_vi:"value",
"user_en":"value",
"email_en":"value"
}
req.body.user_name
is the wrong way to access, because user_name
is a variable, not the key. this will search body object for the key "user_name"
which is an invalid key.
here is the correct way to access through a variable.
use req.body[user_name]
Upvotes: 1
Reputation: 1259
Just access the request body by key:
request.body[key];
In your case:
request.body[user_name];
Will solve the problem!
Upvotes: 0
Reputation: 18557
You are using wrong element name with user_name
which is actually user_en
.
Once try like req.body.user_en
.
Give it a try, it should work.
Upvotes: 1