Nodejs express框架 form表单 action属性
Nodejs express框架 form表单 action属性
form表单的action属性是:规定当提交表单时向何处发送表单数据。怎么样理解这句话? 前端产生表单的文件为:views文件夹下的index.ejs 后端处理表单的文件为:routes文件夹下的handlepost.js文件,那么form表单中的action属性如何填写了?
当然可以。让我们详细讨论一下Node.js、Express框架以及如何配置<form>
表单的action
属性。
理解action
属性
action
属性指定了当用户提交表单时,表单数据将被发送到哪个URL进行处理。例如,如果你的后端处理程序位于/submit
路径上,那么action
属性应该设置为这个路径。
示例结构
假设你的项目结构如下:
myapp/
├── views/
│ └── index.ejs
├── routes/
│ └── handlepost.js
└── app.js
前端文件 index.ejs
在index.ejs
中,你可以创建一个简单的HTML表单,并指定action
属性指向后端处理程序:
<!-- views/index.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Example</title>
</head>
<body>
<h1>Submit a Form</h1>
<form action="/submit" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
在这个例子中,当用户点击提交按钮时,表单数据将被发送到/submit
路径。
后端文件 handlepost.js
接下来,在handlepost.js
中,你需要编写代码来处理这个请求:
// routes/handlepost.js
const express = require('express');
const router = express.Router();
router.post('/submit', (req, res) => {
const username = req.body.username;
const email = req.body.email;
console.log(`Received: Username=${username}, Email=${email}`);
// 处理逻辑...
res.send('Form submitted successfully!');
});
module.exports = router;
主应用文件 app.js
最后,在你的主应用文件app.js
中,引入并使用路由:
// app.js
const express = require('express');
const app = express();
const handlePostRoutes = require('./routes/handlepost');
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: true }));
app.use('/', handlePostRoutes);
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
总结
通过上述配置,你可以在Node.js + Express环境中实现一个简单的表单提交功能。action
属性决定了表单数据提交的目标路径,而后端代码则负责处理这些数据。希望这对你有所帮助!
在express或你用的mvc框架中,将该action,也就是请求路径,指定给handlepost.js去处理就OK。nodejs路由设置入门书籍都有讲的~
action="/do"; router.js var handlepost = require(’./handlepost’); router.post(’/do’,handlepost(req,res));
大概就是这个意思。不要照抄。理解最好。