繁体   English   中英

Node.js/Express 表单发布 req.body 不工作

[英]Node.js/Express form post req.body not working

我正在使用 express 并且无法从 bodyParser 获取表单数据。 无论我做什么,它总是显示为空 object。这是我快速生成的 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 是空的 object {}

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

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

我正在使用节点 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帖子的主体是具有name属性的所有表单控件的键/值哈希值,值是控件的值。

您需要为所有输入命名。

它也是由于内容类型。 请参阅console.log(req)对象。

'content-type': 'application/json; charset=UTF-8’  // valid.

'content-type': 'application/JSON; charset=UTF-8’  // invalid & req.body would empty object {}.

要通过console.log检查内容类型(req.is('json'))//返回true / false

我认为'charset = UTF-8'在上面可以忽略不计。

如果你的表格看起来像这样

<form action="/", method="post">
    <label for="for_name">Name: </label>
    <input id="for_name" type="text" name="user_name"/>
    <button type="submit">Submit</button>
</form>

如果您使用以下代码行

app.use(express.json());

那么 req.body 将是空的,因为它只解析内容类型为application/json的请求,但是来自元素的请求的默认值为application/x-www-form-urlencoded 因此,以下代码行将解决问题

app.use(express.urlencoded({ extended: true }));

我的第一个 StackOverflow 贡献。 好极了!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM