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 文件样式。

广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP