Tuesday, 15 April 2014

Node.js (with express & bodyParser): unable to obtain form-data from post request -



Node.js (with express & bodyParser): unable to obtain form-data from post request -

i can't seem recover form-data of post request sent node.js server. i've set below server code , post request (sent using postman in chrome):

post request

post /api/login http/1.1 host: localhost:8080 cache-control: no-cache ----webkitformboundarye19znvxgzxalvs5c content-disposition: form-data; name="username" jem ----webkitformboundarye19znvxgzxalvs5c

nodejs server code

var express = require('express'); // phone call express var app = express(); // define our app using express var bodyparser = require('body-parser'); app.use(bodyparser.urlencoded({ extended: true })); app.use(bodyparser.json()); app.use(bodyparser()); app.all('/*', function(req, res, next) { res.header('access-control-allow-origin', '*'); res.header('access-control-allow-headers', 'content-type,accept,access_token,x-requested-with'); next(); }); var port = process.env.port || 8080; // set our port var router = express.router(); // instance of express router router.get('/', function(req, res) { res.json({ message: 'i groot!' }); }); // login router.route('/login') .post(function(req, res){ console.log('auth request recieved'); // user name var user = req.body.username; var atoken = gettoken(user); res.json({ 'token':'a_token' }); }); app.use('/api', router); app.listen(port);

the login method tries obtain req.body.username - however, req.body empty. i've seen other cases on describing such behavior none of related answers did apply here.

thanks helping out.

in general, express app needs specify appropriate body-parser middleware in order req.body contain body.

[edited]

if required parsing of url-encoded (non-multipart) form data, json, seek adding:

// set statement near top of module var bodyparser = require('body-parser'); // set these statements before define routes. app.use(bodyparser.urlencoded()); app.use(bodyparser.json());

first, you'll need add together body-parser dependencies property of package.json, , perform npm update.

to handle multi-part form data, bodyparser.urlencoded() body parser not work. see suggested modules here parsing multipart bodies.

node.js post express body-parser

No comments:

Post a Comment