TypeError:无法读取undefined属性(ExpressJS / POST)

时间:2017-06-14 20:19:44

标签: javascript node.js express post body-parser

我看过所有类似的问题,没有一个能为我工作。我有一个节点js app,我无法使用body-parser从表单中打印输入文本。

我的index.ejs:

         <form id="demo-2" method = "POST" action="/search">
<input type="search" name = "searcher" placeholder="Search">
                    </form>

Index.js:

var cool = require('cool-ascii-faces');
var express = require('express');

var app = express();
var pg = require('pg');
var bodyParser = require('body-parser');
var env = require('node-env-file');

app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/views/'));

// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

//app.use(express.bodyParser());


//DIFFERENT APPS - tells them what to do

app.post('/search', function(request, response) {
    //var username = req.body;

    console.log("posted something"+ request.body.searcher);
    response.end("something was posted: "+ request.body.searcher);
});

app.get('/search', function(request, response) {
     response.send("skylarr");

});

尽管使用输入的名称搜索器,我收到错误:TypeError: Cannot read property 'searcher' of undefined

这里有什么问题?

3 个答案:

答案 0 :(得分:5)

body-parser不是快递的一部分。使用npm install body-parser --save单独安装,然后将其用作中间件。检查您评论express.bodyParser()中间件

的行后面的代码
var cool = require('cool-ascii-faces');
var express = require('express');

var app = express();
var pg = require('pg');
var bodyParser = require('body-parser');
var env = require('node-env-file');

app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/views/'));

// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

//app.use(express.bodyParser());

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


//DIFFERENT APPS - tells them what to do

app.post('/search', function(request, response) {
    //var username = req.body;

    console.log("posted something"+ request.body.searcher);
    response.end("something was posted: "+ request.body.searcher);
});

app.get('/search', function(request, response) {
     response.send("skylarr");

});

答案 1 :(得分:1)

标准Node.JS HTTP请求中没有body属性。该密钥由bodyParser中间件修补。

您可以添加bodyParser中间件,或者(如果您不想因某些原因解析正文)使用查询或网址参数来传递searcher

答案 2 :(得分:1)

您缺少身体解析器。你需要告诉express使用body解析器作为中间件。

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

在app.post()上方添加这两行。