简体   繁体   中英

Nodejs post method - req.body.variable undefined

I have the following App.js :

var express = require('express'),
app = express(),
engines = require('consolidate'),
MongoClient = require('mongodb').MongoClient,
assert = require('assert'),
bodyParser = require('body-parser')

app.engine('html', engines.nunjucks);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');

app.use(bodyParser.urlencoded({ extended : true }));
// app.use(bodyParser.urlencoded());
// app.use(bodyParser.json());

app.post('/insert_movie', function (req, res) {

    var movieName = req.body.movie_name;

    console.log(movieName);

});

// No route matching:
app.use(function (req, res) {
    res.sendStatus(404);
});

var server = app.listen(3000, function () {
    var port = server.address().port;
    console.log('Express server listening on port %s.', port);
});

My html page:

<h1> Add new movies</h1>

<form action="/insert_movie" method="POST">

    <input type="text" id="movie_name">
    <input type="text" id="movie_year">
    <input type="text" id="movie_imdb">

    <input type="submit" value="Submit" />

</form>

When I enter values into the text boxes and press submit, my post method is hit ('/insert_movie') . However movieName is undefined not only that but req.body is {}

Can someone explain to me what I'm doing wrong here as I've gone through many solutions on this website however they're all pointing the body parser being incorrectly setup, I've tried the following:

  1. app.use(bodyParser.urlencoded({ extended : true }));
  2. app.use(bodyParser.urlencoded());
  3. app.use(bodyParser.json());

Neither of these fix my issue.

You need to add name attribute to the input elements. That's one of the things your body-parser library needs to parse the form.

<h1> Add new movies</h1>

<form action="/insert_movie" method="POST">
  <input type="text" name="movie-name" id="movie_name">
  <input type="text" name="movie-year" id="movie_year">
  <input type="text" name="movie-url" id="movie_imdb">
  <input type="submit" value="Submit" />
</form>

try to use this

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

app.use(bodyParser.urlencoded({
  limit: '500mb',
  extended: true,
  parameterLimit: 50000
}));
app.use(expressValidator());
app.use(bodyParser.json());

use multer middle ware for req.body

var app = require('express')();
var multer = require('multer);
var upload = multer().any();
 //multer().any() upload both array and file 
//add the multer middle ware in your router  
app.post('/insert_movie',upload,  function (req, res) {
    var movieName = req.body.movie_name;
   console.log(req.body);
    console.log(movieName);

});

you can see the official npm blog https://www.npmjs.com/package/multer

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