bruno_cw
bruno_cw

Reputation: 1031

jQuery + node.js express POST request

I'm trying to send a post request to a node server. This is my client-side code:

function send(userid,message){
    $.ajax({
        method: "POST",
        url: "/chat/messages?id="+userid+'&message='+message
    })
    clear();
}

This is my server side code:

  app.post('/chat/messages',function (req,res){
    var query = url.parse(req.url,true).query
    insertMessage(query.id,query.message)
  })

This works, however I'm not sure getting data in the query string using post is the right way to go.

I tried adding a data field in $ajax parameter:

function send(userid,message){
    $.ajax({
        method: "POST",
        url: "/chat/messages"
        data : {'id' : userid, 'message' : message}
    })
    clear();
}

And using bodyParser() in the server end to parse the body contents:

app.use(bodyParser.json())
app.post('/chat/messages',function (req,res){
    console.log(req.body)
})

but when I log the response, the body{ } object is always empty. Why is that? Is a <form> tag necessary for POST requests?

I tried editing my ajax request to use json as the dataType and stringifying the data, but the req.body is still empty.

$.ajax({
    method: "POST",
    url: "/chat/messages",
    data : JSON.stringify({'id' : userid, 'message' : message}),
    dataType: 'json',
})

Upvotes: 1

Views: 645

Answers (2)

jemiloii
jemiloii

Reputation: 25759

You should read the express documentation. http://expressjs.com/api.html#req

// For regular html form data
app.use(bodyParser.urlencoded())
app.post('/chat/messages',function (req,res){
    console.log(req.body);
    console.log(req.query.id);
    console.log(req.query.messages);
})

You can also do req.params

app.post('/chat/messages/:id',function (req,res){
    console.log(req.body);
    console.log(req.query);
    console.log(req.params.id)
})

Upvotes: 1

Kevin B
Kevin B

Reputation: 95059

When you post data to a server, the data is usually urlencoded and added to the body of the request. In your example, it would look like this:

id=<userid>&message=<message>

Therefore, the bodyparser you need to be able to parse that is bodyparser.urlencoded()

app.use(bodyParser.urlencoded())

Note that it isn't always urlencoded, it all depends on what you are using to send the post. AngularJS for example defaults to sending it as json instead. The good news is you could simply add both bodyparsers and your route won't need to know which method was used since in both cases the data would end up on req.body with key/value pairs.

Upvotes: 2

Related Questions