Friday, 1 July 2016

nodejs express access POST text/plain data

Sometime you don't want to send json to your api. e.g. just a string.

you can actually put it into the url and use GET.

As a good developer, use POST and put into body(data) is the right thing to do.

However, express doesn't support text/plain, it only support:

  • application/json
  • application/x-www-form-urlencoded
  • multipart/form-data

the solution for that is:

app.use(function(req, res, next){
  if (req.is('text/*')) {
    req.text = '';
    req.setEncoding('utf8');
    req.on('data', function(chunk){ req.text += chunk });
    req.on('end', next);
  } else {
    next();
  }
});

Then the data is in req.text.

http://stackoverflow.com/questions/12497358/handling-text-plain-in-express-3-via-connect








No comments:

Post a comment