Express4在POST请求中返回错误

时间:2016-12-26 19:34:36

标签: javascript node.js express

我在POST请求中发现" Express.js返回错误"当我尝试在POST resquest中发送数据时。我怎么解决它?

我的app.js代码:

var express = require('express');
var bodyParser = require('body-parser')
var app = express();
var form = require('./routes/form')(app);

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.listen(7777, function(){
  console.log("Running...")
});

我的form.js代码:

module.exports = function(app){

  app.get('/form', function(req, res){
    res.render('form');
  });

  app.post('/send', function(req, res){
    console.log(req.body.name);
  });

};

我的form.ejs代码:

<form action="/send" method="post">
  <input type="text" name="name" value="">
  <input type="submit" value="Submit">
</form>

控制台错误:

TypeError: Cannot read property 'name' of undefined
    at /home/victor/cam/CAMTalk/routes/form.js:9:25
    at Layer.handle [as handle_request] (/home/victor/cam/CAMTalk/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/victor/cam/CAMTalk/node_modules/express/lib/router/route.js:131:13)
    at Route.dispatch (/home/victor/cam/CAMTalk/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/victor/cam/CAMTalk/node_modules/express/lib/router/layer.js:95:5)
    at /home/victor/cam/CAMTalk/node_modules/express/lib/router/index.js:277:22
    at Function.process_params (/home/victor/cam/CAMTalk/node_modules/express/lib/router/index.js:330:12)
    at next (/home/victor/cam/CAMTalk/node_modules/express/lib/router/index.js:271:10)
    at expressInit (/home/victor/cam/CAMTalk/node_modules/express/lib/middleware/init.js:33:5)
    at Layer.handle [as handle_request] (/home/victor/cam/CAMTalk/node_modules/express/lib/router/layer.js:95:5)

感谢您的关注!

2 个答案:

答案 0 :(得分:1)

当您将中间件传递给应用程序时,您还没有在应用程序上安装它们。首先应该安装中间件至少body-parser负责填充req.body的中间件。所以搬家:

var form = require('./routes/form')(app);

在您的身体解析器中间件之后它应该可以工作。

一般来说顺序很重要

答案 1 :(得分:0)

尝试从输入中删除value=""。我认为你总是以这种方式设置为空。