software_writer
software_writer

Reputation: 4478

Post json using jquery on express server

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?

Upvotes: 2

Views: 808

Answers (1)

Arpit Solanki
Arpit Solanki

Reputation: 9931

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)
}
} )

Upvotes: 4

Related Questions