1

I am having trouble posting a nested JSON object to my node.js server.

Here is what the object should look like:

{
    "name" : "Plan 1", 
    "schedule": [
        {
            "start": 0, 
            "days": [
                {
                    "title" : "Day1"
                }
            ]
        }
    ]
}

Here is my server.js code

router.route('/plans')
    .post(function(req, res) {

        console.log(JSON.stringify(req.body));

        var plan = new Plan();  
        plan.name = req.body.name;
        plan.tagline = req.body.tagline;
        plan.duration = req.body.duration;
        plan.schedule = req.body.schedule;

        plan.save(function(err) {
            if (err)
                res.send(err);
            res.send(plan);
        });
})

And some python code to make the request. (I have tried using Postman and curl and got the same results)

import requests
payload = {"name" : "Plan 1", "schedule": [{"start": 0, "days": [{"title" : "Day1"}]}]}
r = requests.post("http://localhost:5000/plans", data=payload)
print(r.text)

This is what is output by server.js for the JSON.stringify(req.body)

{"name" : "Plan 1", "schedule" : ["start", "days"]}

And then nothing actually gets saved, so print(r.text) outputs:

{}

What is the proper way to go about doing this? I am using MongoDB for storage if that is relevant, but it looks like my server.js is not even receiving the full JSON correctly.

user3783608
  • 857
  • 3
  • 11
  • 20
  • 1
    Welcome to Stack Overflow! I'm not familiar with python, but from my experience : check that the content-type header of your request is set to JSON, if it still doesn't work try stringifying your payload before sending it and parse it on the server. and for the save() function, please show us some code :) – xShirase Oct 12 '14 at 20:27
  • Also, you may want to add the bodyparser middleware if you're using Express – xShirase Oct 12 '14 at 20:28
  • Related: [Post JSON using Python Request](http://stackoverflow.com/questions/9733638/post-json-using-python-request) – Jonathan Lonowski Oct 12 '14 at 20:31

1 Answers1

1

From Python Requests docs: http://docs.python-requests.org/en/latest/user/quickstart/#custom-headers

>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> headers = {'content-type': 'application/json'}

>>> r = requests.post(url, data=json.dumps(payload), headers=headers)

This did the trick for me. Thanks

user3783608
  • 857
  • 3
  • 11
  • 20