I am trying to make a post call from a simple html page to a nodejs, express server which saves the values to a mongo collection.
I am passing two post parameters ie name and email, but at the server I am not getting the passed values.
Server says:
TypeError: Cannot read property 'userName' of undefined. What might be the issue.
This is my html file
<html>
<head>
<script type="text/javascript" src="../scripts/jquery.min.js"></script>
</head>
<body>
<br> User Name :
<input type="text" id="userName" name="userName">
<br>
<br>Email :
<input type="text" id="emailId" name="emailId">
<br>
<br>
<input type="submit" id="addAttrs" value="Add" onclick="addUser()">
</body>
<script type="text/javascript" src="../scripts/client.js"></script>
</html>
This is my client side ajax post call at client.js
function addUser() {
var usrName = document.getElementById("userName").value;
var usrEmail = document.getElementById("emailId").value;
console.log('User name :' + usrName + " Email :" + usrEmail);
var obj = {
'userName': usrName,
'userEmail': usrEmail
};
console.log(JSON.stringify(obj));
$.ajax({
url: '/adduser',
method: 'POST',
data: JSON.stringify(obj),
success: function(data) {
console.log('user created , info :' + data);
},
error: function(data) {
console.log('User creation failed :' + data);
}
});
}
This is my server index.js file
var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
var bodyParser = require('body-parser');
app.use(express.static('public'));
var MongoClient = require('mongodb').MongoClient;
var routes = require('./routes/index');
app.use('/', routes);
app.use(function(req, res, next) {
req.db = db;
next();
});
var myCollection;
var db;
var urlencodedParser = bodyParser.urlencoded({
extended: false
})
var server = app.listen(8081, function() {
db = MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if (err)
throw err;
console.log("connected to the mongoDB !");
myCollection = db.collection('user_collection');
});
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
})
module.exports = app;
This is where I handle the request at router.js file
var express = require('express');
var router = express.Router();
var path = require('path');
router.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '../public/views', 'index.html'));
});
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({}, {}, function(e, docs) {
res.render('userlist', {
"userlist": docs
});
});
});
router.post('/adduser', function(req, res) {
var db = req.db;
console.log(req.body);
var userName = req.body.userName;
var userEmail = req.body.userEmail;
var collection = db.get('usercollection');
collection.insert({
"username": userName,
"email": userEmail
}, function(err, doc) {
if (err) {
res.send("There was a problem adding the information to the database.");
} else {
response = {
message: 'user created successfully',
status: 200
};
res.end(JSON.stringify(response));
}
});
});
module.exports = router;
You should send a json instead of string.Make your ajax like this
Remove
JSON.stringify()
or make thatJSON.parse(JSON.stringify(obj))
since you are sending a string (ie: typeof req.body is string ) instead.
$.ajax({
url: '/adduser',
method: 'POST',
data:obj,
success: function(data) {
console.log('user created , info :' + data);
},
error: function(data) {
console.log('User creation failed :' + data);
}
});
and At your server side. use
app.use(bodyParser.json());
this is very important to parse application/json type.Now i guess i will be working for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.