简体   繁体   English

获取在ajax发布请求中传递的参数

[英]Getting parameters passed in the ajax post request

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. 我正在尝试从一个简单的html页面到一个nodejs快递服务器,这会将值保存到mongo集合。

I am passing two post parameters ie name and email, but at the server I am not getting the passed values. 我传递了两个post参数,即name和email,但是在服务器上我没有传递传递的值。

Server says: 服务器说:

TypeError: Cannot read property 'userName' of undefined. TypeError:无法读取未定义的属性“ userName”。 What might be the issue. 可能是什么问题。

This is my html file 这是我的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>

This is my client side ajax post call at client.js 这是我在client.js的客户端ajax post call

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 这是我的服务器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;

This is where I handle the request at router.js file 这是我在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;

You should send a json instead of string.Make your ajax like this 你应该发送一个json而不是string.Make你这样的ajax

Remove JSON.stringify() or make that JSON.parse(JSON.stringify(obj)) since you are sending a string (ie: typeof req.body is string ) instead. 删除JSON.stringify()或将其JSON.parse(JSON.stringify(obj))因为您要发送的是字符串(即: typeof req.body是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);
        }
    });

and At your server side. 并在您的服务器端。 use app.use(bodyParser.json()); 使用app.use(bodyParser.json()); this is very important to parse application/json type. 这对于解析application / json类型非常重要。

Now i guess i will be working for you. 现在我想我会为你工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM