获取ajax post请求中传递的参数

时间:2016-03-24 06:58:55

标签: javascript ajax node.js express

我正在尝试从简单的html页面到nodejs进行调用,表达服务器将值保存到mongo集合。

我传递了两个帖子参数,即名称和电子邮件,但在服务器上我没有得到传递的值。

服务器说:

  

TypeError:无法读取属性' userName'未定义的。可能是什么问题。

这是我的html文件

 <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>

这是我的客户端ajax post 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);
        }
    });
}

这是我的服务器index.js文件

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;

这是我在router.js文件中处理请求的地方

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;

1 个答案:

答案 0 :(得分:0)

你应该发送一个json而不是string。像这样制作你的ajax

  

删除JSON.stringify()或制作JSON.parse(JSON.stringify(obj)),因为您要发送字符串(例如: typeof req.body is string )。

$.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);
        }
    });
  

并在您的服务器端。使用app.use(bodyParser.json());这对于解析application / json类型非常重要。

     

现在我想我会为你工作。