2

这是我的代码:

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

3 回答 3

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'));
于 2012-12-30T19:27:31.787 回答
1

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

req.body.firstname

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

res.render('index', {fname: req.body.firstname});
于 2012-12-30T19:28:31.653 回答
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);
于 2012-12-30T21:53:39.420 回答