我使用快递时无法获取POST数据

时间:2012-12-30 19:11:39

标签: javascript node.js

以下是我的代码:

var express = require('express');
var app = express();

app.get('/:name', function(req,res){
    res.setHeader('Content-Type','text/html');
    res.send('<form action="/" method="POST"><input type="text" name="self"/><input type="submit"/></form>');
});

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

app.listen(8080);

我调用localhost:8080 / examplename

并在输入中写入内容,然后单击“提交”按钮。它转到localhost:8080,但节点返回错误如下:

TypeError: Cannot read property 'self' of undefined
    at /home/yusuf/Masaüstü/node/ue.js:10:19
    at callbacks (/home/yusuf/Masaüstü/node/node_modules/express/lib/router/index.js:160:37)
    at param (/home/yusuf/Masaüstü/node/node_modules/express/lib/router/index.js:134:11)
    at pass (/home/yusuf/Masaüstü/node/node_modules/express/lib/router/index.js:141:5)
    at Router._dispatch (/home/yusuf/Masaüstü/node/node_modules/express/lib/router/index.js:169:4)
    at Object.router [as handle] (/home/yusuf/Masaüstü/node/node_modules/express/lib/router/index.js:32:10)
    at next (/home/yusuf/Masaüstü/node/node_modules/express/node_modules/connect/lib/proto.js:190:15)
    at Object.expressInit [as handle] (/home/yusuf/Masaüstü/node/node_modules/express/lib/middleware.js:31:5)
    at next (/home/yusuf/Masaüstü/node/node_modules/express/node_modules/connect/lib/proto.js:190:15)
    at Object.query [as handle] (/home/yusuf/Masaüstü/node/node_modules/express/node_modules/connect/lib/middleware/query.js:44:5)

3 个答案:

答案 0 :(得分:4)

您需要启用正文解析器中间件。在配置路由之前插入此内容。

app.use(express.bodyParser());

您还可以在此处配置其他内容,例如视图引擎,静态目录等。例如,

app.set('views', __dirname + '/views');
app.set('view engine', 'swig');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));

答案 1 :(得分:1)

req.body允许您获取POST中发送的数据。然后,您可以使用req.body。[数据名称]来实际访问数据。例如,如果您发送了“名字”:

req.body.firstname

您还可以使用res.render将数据发送到模板页面。例如,这会将firstname发送到您的模板语言呈现的索引页面。

res.render('index', {fname: req.body.firstname});

答案 2 :(得分:0)

你需要bodyParser。这是您的确切代码,添加了解析器,并按预期工作:

var express = require('express');
var app = express();

// parses POST bodies:
app.use(express.bodyParser());

app.get('/:name', function(req,res){
    res.setHeader('Content-Type','text/html');
    res.send('<form action="/" method="POST"><input type="text" name="self"/><input type="submit"/></form>');
});

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

app.listen(8080);