最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pass JSON object to node.js server - Stack Overflow

programmeradmin1浏览0评论

I have a test JSON object as follows

{ Id: 100, plugins: [{ Name: 'Test', Version: '2' }] }

which I created using

var json = {}; 
json.Id =  100;
var plugins = [];
json.plugins = plugins;
json.plugins.push({"Name" : "Test", "Version" : "2"});

I have a client side function making an AJAX post request as follows

function postJSON() {
    $.ajax({
      type: 'POST',
      url: 'features',
      data: json,
      dataType: 'json'
    });
  }

I am trying to read this information on my server by just typing console.log(req) for now but it does't seem to be getting my json object.

app.post("/features", function(req, res) {
    console.log(req);
})

Thanks for help!

I have a test JSON object as follows

{ Id: 100, plugins: [{ Name: 'Test', Version: '2' }] }

which I created using

var json = {}; 
json.Id =  100;
var plugins = [];
json.plugins = plugins;
json.plugins.push({"Name" : "Test", "Version" : "2"});

I have a client side function making an AJAX post request as follows

function postJSON() {
    $.ajax({
      type: 'POST',
      url: 'features',
      data: json,
      dataType: 'json'
    });
  }

I am trying to read this information on my server by just typing console.log(req) for now but it does't seem to be getting my json object.

app.post("/features", function(req, res) {
    console.log(req);
})

Thanks for help!

Share Improve this question asked Jul 2, 2013 at 15:28 dopplesoldnerdopplesoldner 9,53912 gold badges46 silver badges57 bronze badges 1
  • You can create that object by simply writing var json = { Id: 100, plugins: [{ Name: 'Test', Version: '2' }] } – SLaks Commented Jul 2, 2013 at 15:39
Add a ment  | 

2 Answers 2

Reset to default 6

As long as you have the bodyParser() middleware installed, Express should parse the JSON request payload into req.body.

Your creation is wrong. JSON is a key-value based storage, meaning it has the syntax of a hash. Try this:

var json = {}; 
json['Id'] =  100;
var plugins = [];
plugins.push({"Name" : "Test", "Version" : "2"});
json['plugins'] = plugins;
发布评论

评论列表(0)

  1. 暂无评论