Node.js 提供的 HTML 頁面服務


到目前為止,我們已經直接從響應物件的 send(0 函式傳送 HTML 程式碼。為了傳送較大的程式碼,我們肯定需要一個單獨的檔案來儲存 HTML 程式碼。

sendFile() 函式−

響應物件提供了一個 sendFile() 函式來向客戶端返回一個 HTML 檔案。

如何在 sendFile() 中提供 HTML 檔案的路徑?

我們匯入 node.js 的 path 核心模組。

const path = require(‘path’);

path 有一個 join 函式。__dirname 是一個全域性變數,儲存著專案主資料夾的實際路徑。

path.join(__dirname, ‘views’, ‘add-user.html’); 這將指向 add-user HTML 程式碼的實際檔案位置。

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);

route.js

const path = require('path');
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>'); res.sendFile(path.join(__dirname, 'views', 'add-   user.html'));
});
router.post('/post-username', (req, res, next)=>{
   console.log('data: ', req.body.username);
   res.send('<h1>'+req.body.username+'</h1>');
});
module.exports = router;

add-user.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>
      <form action="/test/post-username" method="POST">
      <input type="text" name="username">
      <button type="submit"> Send </button>
   </form>
</body>
</html>

在執行 app: npm start 後

瀏覽器輸出:localhost:3000/test/add-username

透過使用 path 模組,它可以在任何型別的作業系統上工作,而不會出錯。每個作業系統都有不同的處理路徑的方法,所以 path 模組會處理好它。

更新時間:2020 年 5 月 13 日

2000 多次瀏覽

開啟您的職業生涯

完成課程以獲得認證

開始
廣告