express.js 中篩選路徑和建立 html 頁面
我們添加了 express 路由器來處理路由。單個路由器檔案處理多個路由。
在 App.js 中為路由器新增路徑 −
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const route = require('./routes');
const app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use('/test',route);
app.use((req, res,next)=>{
res.status(404).send('<h1> Page not found </h1>');
});
const server = http.createServer(app);
server.listen(3000);在路由器中介軟體中,我們使用路徑 −/p>
app.use('/test',route);路由器將處理以 /test 開頭的所有路徑,例如 /test/add-username
我們必須更改 routes.js 檔案中表單中的操作 −
router.get('/add-username', (req, res,next)=>{
res.send('<form action="/test/post-username" method="POST"> <input type="text" name="username"> <button type="submit"> Send </button> </form>');
});Routes.js 檔案 −
const express = require('express');
const router = express.Router();
router.get('/add-username', (req, res,next)=>{
res.send('<form action="/test/post-username" method="POST"> <input type="text" name="username"> <button type="submit"> Send </button> </form>');
});
router.post('/post-username', (req, res, next)=>{
console.log('data: ', req.body.username);
res.send('<h1>'+req.body.username+'</h1>');
});
module.exports = router;這種新增路由器過濾機制有助於將常見的 URL 處理程式放在一個部分中。
在 vs 程式碼編輯器中建立 html5 頁面−
建立新資料夾來儲存 html 頁面,例如 views 資料夾。建立一個新檔案 add-user.html。
在 add-user.html 檔案中,如果我們鍵入 html 並按下 ctrl + 空格,我們將獲得一個為 html5 建立預設框架的選項。選擇它後,我們將得到以下 html5 頁面 −
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> </body> </html>
我們可以在 html 主體中複製 routes.js 檔案中的表單。
<form action="/test/post-username" method="POST"> <input type="text" name="username"> <button type="submit"> Send </button> </form>
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP