2

I want to post a json object to express server.

Javascript

var task = {
    task: "Do something",
    deadline: "5 am"
};

$.post("http://localhost:3000/api/tasks", task, (data) => {
    console.log(data);
}, "json")

Node.js/Express

var bp = require('body-parser')

app.use(bp.json());

app.post('/api/tasks', (req, res) => {
    console.log(req.body);
    res.json(req.body);
})

When I test the server using Postman, I get the expected output, i.e. it displays the task object in the console and also sends it back to the client.

But when I run the above javascript code, it displays an empty object in the console and sends back empty object. What am I missing in the jquery ajax call?

4
  • 1
    You aren't sending json. $.ajax default is application/x-www-form-urlencoded Commented Jul 13, 2017 at 17:38
  • isn't task a json object? Commented Jul 13, 2017 at 17:39
  • No such thing as a json object. json is a string data format Commented Jul 13, 2017 at 17:39
  • Okay, so what do I have to do instead? Commented Jul 13, 2017 at 17:39

1 Answer 1

4

Try adding the application/json header in your request.

$.ajax({ url: 'URL', 
type: 'POST',
contentType: 'application/json', 
data: JSON.stringify(DATA),
success: function(res) {
console.log(res)
}
} )
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! that worked. Is there a way to achieve the same using $.post(), instead of $.ajax()?
$.post will just be a shorthand that's all $.ajax will also work.
can you please add the code snippet using $.post() to your answer? I am not sure what's the correct syntax to set contentType in $.post()
There is no way to add headers using $.post you must use $.ajax. also you can parse the results using JSON.parse if you are sending a json response refer here

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.