5

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!

1
  • You can create that object by simply writing var json = { Id: 100, plugins: [{ Name: 'Test', Version: '2' }] } Commented Jul 2, 2013 at 15:39

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Slaks! I made the amateur mistake of forgetting to add bodyParser() P.S - I am going to dynamically build up the JSON object based on the plugins installed by the user so that was for illustration purposes only
0

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;

4 Comments

That is not true; his JSON is perfectly fine. There is no difference between dot notation and indexer notation.
Oh, really? The way I was taught, I was told that this was the proper syntax. I didn't know you could do it two different ways
You were taught incorrectly. You should only use indexer notation if you're passing a variable (someObject[someVar]). Otherwise, you should always use ..
Yep Slaks is correct. Even your code results in the same JSON object as mine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.