各個(gè)文件
根目錄下的app.js文件中
const express = require('express')
const ejs = require('ejs');
const bodyParser = require('body-parser');
const app = express()
const port = 3000;
// 引入路由模塊
const login = require('./routers/login')
//配置模板引擎
app.engine("html",ejs.__express)
app.set("view engine","html")
//配置靜態(tài)web目錄
app.use(express.static("static"))
//配置第三方中間件,此處配置的bodyParser是全局的配置蔓搞,在下面的login中間件中是可以直接使用的
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
// 當(dāng)訪問(wèn)/login路由時(shí)直接使用login路由模塊
app.use('/login',login);
app.get('/', (req, res) => {
res.send('首頁(yè)')
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
在routers/login.js文件中
const express = require('express');
var router = express.Router();
router.get('/',(req,res)=>{
res.render('login',{})
})
router.post('/doLogin',(req,res)=>{
var body = req.body;
console.log(body);
res.send('用戶名為: '+body.username)
})
module.exports = router;
此時(shí)在頁(yè)面中訪問(wèn)的 /login 、/login/doLogin都會(huì)走routers/login.js中的邏輯
在views/login.html文件中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/css/style.css">
<title>Document</title>
</head>
<body>
<h2>post提交數(shù)據(jù)</h2>
<form action="/login/doLogin" method="post">
用戶名:<input type="text" name="username" id="">
密碼:<input type="password" name="pwd" id="">
<input type="submit" value="提交">
</form>
</body>
</html>