post - Node.js/Express 表单发布 req.body 不起作用

标签 post node.js express

我正在使用 express,但无法从 bodyParser 获取表单数据。无论我做什么,它总是作为一个空对象出现。这是我快速生成的 app.js 代码(我唯一添加的是底部的 app.post 路由):

var express = require('express');

var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); 
});

app.configure('production', function(){
    app.use(express.errorHandler()); 
});

// Routes

app.get('/', function(req, res){
    res.sendfile('./public/index.html');
});

app.post('/', function(req, res){
    console.log(req.body);
    res.sendfile('./public/index.html');
});

app.listen(3010);

这是我的 HTML 表单:

<!doctype html>
<html>
  <body>
<form id="myform" action="/" method="post" enctype="application/x-www-form-urlencoded">
  <input type="text" id="mytext" />
  <input type="submit" id="mysubmit" />
</form>
  </body>
</html>

当我提交表单时,req.body 是一个空对象 {}

值得注意的是,即使我从表单标签中删除 enctype 属性也会发生这种情况

...我有什么遗漏/做错了吗?

我正在使用 Node v0.4.11 并表示 v2.4.6

最佳答案

<form id="myform" action="/" method="post" enctype="application/x-www-form-urlencoded">
  <input type="text" name="I_appear_in_req_body" id="mytext" />
  <input type="submit" id="mysubmit" />
</form>

HTTP post 的正文是所有具有 name 属性的表单控件的键/值哈希,值是控件的值。

您需要为所有输入命名。

关于post - Node.js/Express 表单发布 req.body 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7522034/

相关文章:

javascript - 有没有办法让 Ubuntu 服务器在 NPM 进程失败时自动重新启动?

node.js - 使用 Mongoose 在 Node js中连接多个mongo db数据库

html - 如何配置我的 HTML 以使用 i18next?

ruby - 用 ruby​​ 发送 POST?

iOS 在同一请求中发送 POST 和 GET

node.js - 从sql server获取两个日期之间的数据

node.js - 从 Node.JS 中的中间件函数返回对象

javascript - 如何查找 NodeJS 上是否存在 Azure 文件

jquery - 我如何在 Django 中使用 jQuery/Ajax 进行 POST?

c# - 为什么我的 C# 客户端在发布到我的 WCF REST 服务时返回 (400) Bad Request?