将jQuery JSON对象发布到NodeJs Restify

Oxn*_*rth 5 ajax json node.js restify

我想知道为什么很难在一个简单的JSON字符串中发布/:parameter以解决问题.我遵循了许多例子,但没有发现任何具体的东西.

我在前端有以下代码.

$("#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);
    });


});
Run Code Online (Sandbox Code Playgroud)

如果我在后面连接param,我在发送简单文本方面是成功的j/.但我要发送的是这样的对象,{hello:"world"}并在nodeJS中重新构建它并使用它.

- 编辑:

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)
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

0X

Oxn*_*rth 6

我终于搞定了.

- 前端代码

$("#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);
        });


    });
Run Code Online (Sandbox Code Playgroud)

NodeJs服务

/* 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)
Run Code Online (Sandbox Code Playgroud)