Post jQuery JSON Object to NodeJs Restify

半城伤御伤魂 提交于 2020-02-01 04:58:05

问题


I want to know why it is so hard to post a simple JSON string in a /:parameter to restify. I have followed many examples but have not found anything concrete.

I have the following code in the front end.

$("#btnDoTest").click(function() {

    var jData = {
        hello: "world"
    };
    var request = $.ajax({
        url: "http://localhost:8081/j/",
        async: false,
        type: "POST",
        data: JSON.stringify(jData),
        contentType: "application/javascript",
        dataType: "json"
    });


    request.success(function(result) {

        console.log(result);

    });

    request.fail(function(jqXHR, textStatus) {
        alert("Request failed: " + textStatus);
    });


});

I am succesful in sending simple text if I concatenate the param after the j/. But what I want to send is an object like this {hello:"world"} and reconstruct it back in nodeJS and work with it.

--Edit:

This is my nodejs file
/* the below function is from restifylib/response.js */
var restify = require("restify");

/* create the restify server */
var server = restify.createServer({

});


server.use(restify.bodyParser({ mapParams: true }));

server.use(
  function crossOrigin(req,res,next){
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    return next();
  }
);


 server.post('/j/', function (req, res, next) {


   //res.send(201,"REceived body: "+JSON.stringify(req.params));
   res.send(201,"REceived body: "+JSON.stringify(req.params));
   return next();
 });


var port = 8081;
server.listen(port);
console.log("Server listening on port " +port)

Any help would be appreciated thanks.

0x


回答1:


I finally got it working.

--Front end code

$("#btnDoTest").click(function() {



        var request = $.ajax({

            url: "http://localhost:3000/j",
            async: false,
            type: "POST",
            data: {
                blob: {wob:"1",job:"2", ar:[1,2,{a:'b'}]}
            },

            contentType: "application/x-www-form-urlencoded", //This is what made the difference.
            dataType: "json",

        });


        request.success(function(result) {

            console.log(result);

        });

        request.fail(function(jqXHR, textStatus) {
            alert("Request failed: " + textStatus);
        });


    });

NodeJs services

/* the below function is from restifylib/response.js */
var restify = require("restify");

/* create the restify server */
var server = restify.createServer({

});


server.use(restify.bodyParser());
server.use(restify.CORS());


server.post('/j/', function(req, res, next) {

    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");

    // req.params  == data on jquery ajax request.


    res.send(200, JSON.stringify(req.params));
    console.log(req.params.blob.ar[2].a)



    res.end();
    return next();
});


var port = 3000;
server.listen(port);
console.log("Server listening on port " + port)



回答2:


Don't stringify it. Try this, note the two changes, I removed the JSON.stringify and switched to application/json, as its JSON and not JavaScript.

var request = $.ajax({
    url: "http://localhost:8081/j/",
    async: false,
    type: "POST",
    data: jData,
    contentType: "application/json",
    dataType: "json"
});

application/javascript should only be used when doing JSONP.




回答3:


my answer first!

jquery:

$.ajax({
    url: url,
    method: 'post',
    data: JSON.stringify({key:value}),
    contentType: "application/json"
});

node http:

server.post('/1', function(req, res) {
  var body = req.body;
  var dataValue = body.dataKey;
});

why?

data of $.ajax is just for what to send to server end, its datatype has not be defined, so when use JSON.stringify({key:value}), the data will be sent as a string like '{key:"xxx"}', and node recieve a string, not a json object even the string structure looks like a json. but after we add contentType: "application/json" in $.ajax, when node recieve the data, it will be a real json object type data.



来源:https://stackoverflow.com/questions/16922379/post-jquery-json-object-to-nodejs-restify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!