gpt4 book ai didi

javascript - Node.js - 提交表单不控制表单值

转载 作者:行者123 更新时间:2023-11-30 10:18:56 26 4
gpt4 key购买 nike

我是 node.js 的初学者。我正在尝试使用表单添加“名称”和“部门”。单击提交后,我同时安慰了“姓名”和“部门”,但我得到的“两者”都是“未定义的”。

我不知道我做的衣服在哪里。有谁知道并帮助我安慰名字和部门吗?

这是我的表格:

<form method="post" role="form" class="form-horizontal" enctype='multipart/form-data'>
<div class="form-group">
<label for="name"><input id='name' name='name' placeholder='Enter your name' type="text" ></label>
<label for="dept"><input id='dept' name='dept' placeholder='Enter your department here' type="text"></label>
<button type='submit' class="btn btn-default" id='submit'>Submit your Details</button>
<div>
</form>

这是我的 app.js

var
http = require('http'),
express = require('express'),
routes = require('./routes'),
userList = require('./routes/list'),
path = require('path'),

app = express();

app.set('port', process.env.PROT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(app.router);
app.use(express.static(path.join(__dirname, 'static')));


app.get('/', routes.list);
app.get('/addList', userList.addList);
app.post('/addList', function(req, res){
var name = req.params.name;
var dept = req.params.dept;

console.log(name, dept);//getting undefined why?
});

http.createServer(app).listen(app.get('port'), function(){
console.log('successfuly initiated!');
});

更新的表单和 app.js

表格:

<form method="post" role="form" class="form-horizontal" action="/addList">
<div class="form-group">
<label for="name"><input id='name' name='name' placeholder='Enter your name' type="text" ></label>
<label for="dept"><input id='dept' name='dept' placeholder='Enter your department here' type="text"></label>
<p><input type='submit' class="btn btn-default" id='submit' value='Submit your Details'/></p>
<div>

应用程序.js

var
http = require('http'),
express = require('express'),
routes = require('./routes'),
userList = require('./routes/list'),
path = require('path'),

app = express();

app.set('port', process.env.PROT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');


app.use(app.router);
app.use(express.static(path.join(__dirname, 'static')));
app.use(express.bodyParser()); //newly added
app.use(express.urlencoded()); //newly added

app.get('/', routes.list);
app.get('/addList', userList.addList);
app.post('/addList', function(req, res){
var name = req.body.name;
var dept = req.body.dept;

console.log(name, dept);

});

http.createServer(app).listen(app.get('port'), function(){
console.log('successfuly initiated!');
});

最佳答案

您的表单缺少 action="/addList" 属性

另外,由于您是使用方法 POST 发布的,因此您的值将在正文中

var name = req.body.name;
var dept = req.body.dept;

要在正文中显示值,请添加此中间件

app.use(express.bodyParser());
app.use(express.urlencoded());

app.use(app.router) 应该是您调用的最后一件事。

关于javascript - Node.js - 提交表单不控制表单值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22299493/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com