Node.js 中 HTML 頁面的樣式


在 HTML 檔案中,我們可以在 head 部分中簡單地新增樣式 −

<html>
   <head>
      <style>
         //add css code
      </style>
   </head>
<body>
</body>
</html>

我們也可以直接在 HTML 中新增內聯 css 樣式。

通常 css 與 HTML 程式碼分離。第三種新增 css 的方法是包含一個 css 檔案。

如何在 Node.js 中提供靜態檔案?

通常 css 檔案會新增以下標籤 −

<head>
   <link rel=”stylesheet” href=”path-to-css-file”>
</head>

Express js 提供了一箇中間件來提供靜態檔案。該中介軟體對給定的資料夾具有讀訪問許可權。

app.use(express.static(path.join(__dirname, ‘public’)));

path:這是 node.js 中的核心模組

__dirname:專案根資料夾的實際路徑

Public:具有從 node 服務端讀取訪問許可權的資料夾名

Css 檔案將儲存在 public 資料夾中。

css 檔案示例用法 −

App.js

const http = require('http');
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const route = require('./routes');
const app = express();
app.use(bodyParser.urlencoded({extended: false})); app.use(express.static(path.join(__dirname, 'public')));
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);

在主專案資料夾中建立 public 資料夾,並在其中的 css 資料夾下儲存一個 main.css 檔案。

Main.css

input {
   width:200px;
   height:20px;
}

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

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
      <link rel="stylesheet" href="/css/main.css">
   </head>
<body>
   <form action="/test/post-username" method="POST"> <input type="text" name="username"> <button          type="submit"> Send </button> </form>
</body>
</html>

執行:npm start

瀏覽:localhost:3000/test/add-username,我們更新輸入欄位的 css 檔案樣式。

更新於: 13-May-2020

檢視次數:7K+

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告