node.js - Expressjs POST 错误 : TypeError: Cannot read property 'title' of undefined

标签 node.js post express

我做了很多尝试来弄清楚为什么会引发这个错误:

Configuring
Listening on 2000
TypeError: Cannot read property 'title' of undefined
   at /home/abdulsattar/learning/node/express/index.js:9:20

index.js:

var express = require("express"),
    app = express.createServer();

app.get("/", function(req, res) {
  res.send('<form action="/new" method="post"><input type="text" name="title" /><input type="submit" /></form>');
});

app.post("/new", function(req, res) {
  res.send(req.body.title);
});

app.configure(function() {
  console.log("Configuring");
  app.use(express.bodyParser());
});

var port = process.env.PORT || 2000;

app.listen(port, function() {
  console.log("Listening on " + port);
});

我读到 express 需要 bodyParser()。我在上面使用它,但它总是失败。我在 2.5.82.5.8 版本上尝试过(认为这可能是问题所在),但在两个版本上都失败了。有什么我想念的吗?

最佳答案

我的直觉,尝试将 app.configure 语句移到 app.get 和 app.post 之前。 bodyParser 中间件未被调用。此外,为了安全起见,将 enctype 添加到表单中,这不是必需的,但无论如何:application/x-www-form-urlencoded

让我知道...

关于node.js - Expressjs POST 错误 : TypeError: Cannot read property 'title' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9348250/

相关文章:

node.js - 依次执行node.js代码

Django:表单 GET 有 "field required"错误,而 POST 没有

javascript - 发布请求正文为空 - XMLHttpRequest 到 Express 服务器

javascript - Express js在React客户端中发送文件并下载

javascript - 通过Heroku获取客户端IP地址

JavaScript 生成器风格的异步

node.js - 将 Nightmare 包裹在 promise 中/一次处理一个网址

sql - 如何在 Sequelize 查询中使用查询参数作为列名

javascript - Axios post 为对象添加额外的键

php - 在不使用 SSL 的情况下防止数据包嗅探的最佳方法是什么?