【问题标题】:Accessing parameters from nodeJS/ExpressJS sent from html form by POST Method通过 POST 方法访问从 html 表单发送的 nodeJS/ExpressJS 的参数
【发布时间】:2013-03-12 19:08:45
【问题描述】:

我想知道从 HTML 表单访问通过 post 方法发送的参数的命令

我已经尝试了所有这些,但它们会打印 undefined 或发回 error ...

编辑 1: 忘了说,我也加了这个server.use(express.bodyParser());

编辑 2:

var express = require('express'),
server  = express(),
client  = require('mysql').createConnection({ host:'localhost', user:'root', password:'password' });

在 MySQL 中使用 dbCRUD 进行休息服务

var dbcrud  = require('dbcrud').init(client, 'contacts', model);

然后我做一个

server.use(express.bodyParser());

post 功能在这里执行..

server.post('/families',function(req,res){
    console.log(req.id);
    console.log("1: " + req.param.id);
    console.log("2: " + req.params.id);
    console.log("3: " + req.param("id"));
    console.log("4: " + req.params('id'));
    console.log("5: " + req.params[0]);
    console.log("6: " + req.body.name);
    console.log("7: " + req.body.notes);
    console.log("8: " + req.body.id);
    //console.log("5: " + req.params[0]);
    res.send('Hello POST : families');
});

我在这里添加路线...

dbcrud.addRoutes(server);

在 HTML 表单中,我为输入标签指定了 id 和 name 属性...

<form method="post" action="http://10.180.218.72:3000/families">
   id    : <input type="number" id="id" name="id"></input>
   name  : <input type="text" id="name" name="name"></input>
   notes : <input type="text" id="notes" name="notes"></input>
           <input type="submit" value = "submit" ></input>
</form>

【问题讨论】:

  • 你能发布更多你的代码吗?或者至少 order 中间件、路由和 app.listen 出现在您的代码中?
  • 已编辑,请看

标签: node.js rest express


【解决方案1】:

在您的代码中尝试app.use(express.bodyParser());。 bodyParser 是一个用于解析 post 请求正文的快速中间件。

【讨论】:

  • 还将 enctype="application/x-www-form-urlencoded" 添加到您的表单 html 代码中
  • app.use(express.bodyParser())放在您的任何路线之前。
猜你喜欢
  • 1970-01-01
  • 2013-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-13
  • 2015-08-04
  • 2011-05-11
相关资源
最近更新 更多