nodejs express, ajax posting w/ jquery and receiving response

前端 未结 3 1395
轻奢々
轻奢々 2020-12-23 10:34

Having some trouble getting express to respond properly to my jquery ajax request. The actual posting is working fine, but no matter what I try I cant seem to actually get a

3条回答
  •  执念已碎
    2020-12-23 11:05

    Pastor Bones' comment was particularly important to me, as I was using $.ajax to post to a Node server. My relevant portion of code ended up like this:

    // Incoming parameter "teams" is an array of objects
    function saveTeams(teams) {
        var xhr;
        var data = JSON.stringify({ teams: teams });
    
        xhr = $.ajax({
            type: "POST",
            url: "http://localhost:8000/saveteam",
            contentType: "application/json",
            data: data,
            headers: {
                Authorization: "..."
            }
        });
    
        return xhr;
    } 
    

    Note that the contentType header is relevant for the parsing to work.

    On the node server side, I can process the payload like this:

    saveTeams: function (req, res, next) {
        var teams = req.body.teams;
    
        if (teams.length > 0) {
            console.log("Teams to be added:");
            for (var i = 0; i < teams.length; i++) {
                console.log(teams[i]);
                // ...
            }
        }
        // ...
    }
    

提交回复
热议问题