简体   繁体   中英

Issue sending json array via ajax to nodejs server

I'm sending via AJAX to my server nodejs, with this JS on client side:

function login(){
    var array=[];
    var jsonData={};
    jsonData.user=$('#user').val();
    jsonData.pass=$('#pass').val();
    array.push(jsonData);
    console.log(JSON.stringify(array));
    $.ajax({
        method:'POST', 
        url: 'auth',
        dataType: 'application/json',
        data: JSON.stringify(array)
    }).done(function(msg){
        alert( "Data Saved: " + msg );
    });
}

As can you see, before send ajax, the browser output console is:

[{"user":"User001","pass":"SecretPassword"}]

On server side, I have this code:

router.post('/', function(req, res, next){
    console.log(req.body); 
    // { '[{"user":"User001","pass":"SecretPassword"}]': '' }

    console.log(JSON.parse(req.body));   
    // {"[{\"user\":\"User001\",\"pass\":\"SecretPassword\"}]":""}


    res.sendStatus(202);
}

But, if I test this web service with Postman, my server receives Json data correctly: Screen capture

Please, does anyone help me??, I trying solve this about 2 days:(

Don't stringify data, it's supposed to be an object, so you can send jsonData directly:

function login(){
    var array=[];
    var jsonData={};
    jsonData.user=$('#user').val();
    jsonData.pass=$('#pass').val();
    array.push(jsonData);
    console.log(JSON.stringify(array));
    $.ajax({
        method:'POST', 
        url: 'auth',
        dataType: 'application/json',
        data: jsonData // << here
    }).done(function(msg){
        alert( "Data Saved: " + msg );
    });
}

var invoiceJson = {name: "abc"};

$.ajax({
    url: url,
    type: "POST",
    dataType: "json",
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(invoicejson),
    success: (data) => {
        try {
            console.log( data);
        } catch (err) {
            console.log( err);
        }
    }
})

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.

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