如何使用jquery ajax和node js在express框架中将数据从客户端传递到服务器?

时间:2018-01-26 11:29:16

标签: javascript jquery node.js ajax express

问题出在我打电话的时候         server.js保存我需要将数据从client.js传递到server.js的详细信息。但是,如果我传递JSON对象数组但是接收它是否是单个JSON对象,则服务器不理解数据。     我试图在控制台中打印cart_items数组,它是未定义的。

            //my client.js code
            var server_url = "http://127.0.0.1:9000";

            $(document).ready(function () {

                var cart_items = [{
                    id: '1',
                    item: 'rice',
                    cost: 25
                }, {
                    id: '2',
                    item: 'roti',
                    cost: 35
                }, {
                    id: '3',
                    item: 'curry',
                    cost: 40
                }]

                cart_items = JSON.stringify(cart_items);
                var menu_item = ['rice', 'roti', 'curry'];
                // $("body").append($newdiv1, [newdiv2, existingdiv1]);
                console.log(cart_items)
                for (let i = 0; i < 3; i++) {

                    console.log("jadsnkjn")
                    var $newInput = document.createElement("input");
                    $newInput.setAttribute('type', 'checkbox')
                    $newInput.setAttribute('class', 'optionIn')
                    $newInput.setAttribute('id', 'item' + i)

                    var $newLabel = document.createElement("label");
                    $newLabel.setAttribute('for', 'item' + i);
                    $('#item' + i).text(menu_item[0]);
                    $(".first_row").append($newInput, $newLabel);

                }



                $('.proceed_btn').on('click', function () {

                    $.ajax({
                        url: server_url + "/save",
                        type: "POST",

                        data: cart_items,
                        success: function (msg) {

                            alert("Local success callback.fggdfg" + msg);
                        },
                        error: function (jqXHR, status, err) {
                            alert("Local error callback.");
                        }
                    })
                })



            })


    ----------


            //my server.js code  
            var express = require('express')
        var bodyParser = require('body-parser')
        var server = express();
        var cors = require('cors');
        var mysql = require('mysql');
        var port = 9000;
        server.use(cors())
        server.use('/scripts', express.static(__dirname + '/scripts'))
        server.use('/css', express.static(__dirname + '/css'))
        server.use(express.static(__dirname))
        server.use(bodyParser.urlencoded({ extended: true }))
        server.use(bodyParser.json());


        //Saving the cart details in the database table order_details
        server.post('/save', function (req, res) {
            var error = 0;
            var status_code = 200;
            var status_message = "callback success";
            var cart_items = []
            cart_items = req.body;// I think I am missing somethings here I tried with cart_item = req.body.cart_items still undefined
            console.log(cart_items[0].id)//giving undefined

            //initiating database insertion
            //dbInsertion(cart_items);


            return res.status(status_code).send(status_message);
        })



        //inserting the order details in order_details table after successful payment
        function dbInsertion(cart_items) {
            var connectionObject = dbConnection();

            sql = "insert into order_details values ('" + cart_items[0].id + "','" + 908089 + "')";
            connectionObject.query(sql, function (err, result) {
                if (err) {
                    error = error + 1;
                    status_code = 404;
                    error_message = "Sorry data could not be entered something is wrong in the sql query syntax";
                    console.log("error in the sql query" + status_code)

                }
                else console.log("1 row inserted");


            })
            connectionObject.end();
        }

        //establishing the connection with database 
        function dbConnection() {
            var con =
                mysql.createConnection({
                    host: "localhost",
                    user: "root",
                    password: "root",
                    database: "tempdb"

                })
            con.connect(function (err) {
                if (err) throw err;
                console.log("connected!")
            })

            return con;
        }


        server.listen(port, function () {
            console.log("listening at" + port);
        })




    ----------




            // this is my index.html page

                <html>

                <head>
                    <title>
                        Eatback
                    </title>

                </head>

                <body>
                    <input type="text" id="key" name="key">
                    <input type="text" id="value" name="value">
                    <button id="button" class="btn btn-success">submit</button>
                    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
                    <script src="scripts/client.js"></script>
                    <div id="new">

                    </div>
                </body>

                </html>

2 个答案:

答案 0 :(得分:1)

您的代码没问题,您只需删除此行:

cart_items = JSON.stringify(cart_items);

并将您的数据作为对象发送:

data: { cart_items: cart_items },

无需将提交的数据转换为json字符串,如果这样做,则应将其解析为服务器中的对象:

var cart_items = JSON.parse(req.body);

答案 1 :(得分:0)

答案是,在ajax调用数据段中,它应该是数据:{cart_items:cart_items}而不是数据:cart_items