Nodejs post方法 - req.body.variable undefined

时间:2017-08-09 11:32:14

标签: javascript node.js express

我有以下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);
});

我的html页面:

<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>

当我在文本框中输入值并按提交时,我的帖子方法会被点击('/insert_movie')。但是movieName未定义,但req.body{}

有人可以向我解释我在这里做错了什么,因为我在这个网站上经历了很多解决方案,但他们都指出身体解析器设置不正确,我已经尝试了以下内容:

  1. app.use(bodyParser.urlencoded({extended:true}));
  2. app.use(bodyParser.urlencoded());
  3. app.use(bodyParser.json());
  4. 这些都没有解决我的问题。

3 个答案:

答案 0 :(得分:2)

您需要将name属性添加到输入元素。这是您的body-parser库需要解析表单的事情之一。

<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>

答案 1 :(得分:0)

尝试使用此

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

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

答案 2 :(得分:0)

  

使用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);

});

你可以看到官方的npm博客 https://www.npmjs.com/package/multer