简体   繁体   中英

NodeJS Request Body Empty

I'm using node with express@4.13.4 and body-parser@1.13.3.

My jade page has for instance this property:

input(type='text',class='form-control', placeholder="Username", name='username', id="username")

The JavaScript code looks like this:

var bodyParser = require('body-parser');

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();
var favicon = require('favicon')
app.use(bodyParser.json());

app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use( function(req, res, next){
app.locals.pretty = true
  next()
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(express.static(path.join(__dirname, 'public')));
app.get('/create', function(req,res) {
  res.render("create");
});

app.get('/creation', function(req,res) {
  console.log("creation")
  console.log(req.body)
});

The create page is the first opened and there is also the input field username, but the request body is empty in the /creation function. Can anyone help ?

You need to submit the form using POST method and alter the function:

app.post('/creation', function(req,res) {
  console.log("creation")
  console.log(req.body); // here will show the values of inputs submited
});

More about express routes.

As we understood body parse will work on the submit of the form or json with POST request. in this case make sure you are submitting the form correctly, you can see the POST request in firebug or other tool. Once its done correctly you will be able to see the body elements by req.body.username

you can have simple form like.

<form action='post' ..>
  <input name='username' ..>
  <input type='submit' ..>
</form>

Also I seen two times middleware app.use(bodyParser.json()); use. in case you missed it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM