1.0、静态资源和动态资源
1.1、静态资源
- 一般客户端发送请求到web服务器,web服务器从内存在取到相应的文件,返回给客户端,客户端解析并渲染显示出来。
1.2、动态资源
- 一般客户端请求的动态资源,先将请求交于web容器,web容器连接数据库,数据库处理数据之后,将内容交给web服务器,web服务器返回给客户端解析渲染处理。
1.3、两者区别
- 静态资源一般都是设计好的html页面,而动态资源依靠设计好的程序来实现按照需求的动态响应;
- 静态资源的交互性差,动态资源可以根据需求自由实现;
- 在服务器的运行状态不同,静态资源不需要与数据库参于程序处理,动态可能需要多个数据库的参与运算。
2.0、实现思路
- 使用http模块,创建一个服务器;
- 根据请求路径,使用fs模块,读取对应的文件,返回给浏览器。
3.0、实现过程
3.1、静态资源
-
common.css
h1 { color: #ff0 !important; cursor: pointer; }
-
main.js
const static = document.getElementById('static') static.style.backgroundColor = '#ccc' static.onclick = () => { console.log('main.js') }
-
index.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"> <title>Document</title> <link rel="stylesheet" href="./common.css" /> </head> <body> <h1 id="static">静态资源服务器</h1> </body> <!--引入外部的js文件--> <script type="text/javascript" src="./main.js" ></script> <style> h1 { color: #0ff; text-align: center; } </style> </html>
3.2、file协议预览效果
3.3、简单搭建静态资源服务器
-
脚本代码
// 提供一个http 服务 const http = require('http'); // fs 模块 用于读取文件的 const fs = require('fs') // 创建一个服务 const server = http.createServer((request,response)=>{ let pathname = request.url //先获取地址 pathname=pathname=='/'?'/index.html':pathname //根目录下定位到首页 console.log(pathname) // 读取目标文件 fs.readFile('.' + pathname, (err,data)=>{ if (err) { response.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' }); response.end('<h3>404</h3>'); } else { response.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' }); response.end(data); } } ) }) server.listen(9999)
-
效果
-
缺陷
- 从图片直观能看出,通过http协议 和 file协议 访问的结果不一样
-
导致原因
- 上面脚本里边可以看出我们处理响应数据的时候,设置响应头
'Content-Type'
是text/html
- 所以,浏览器解析文件的时候都是以
text/html
解析的,就会出现除html文件外,其他文件失效、错误的问题
- 上面脚本里边可以看出我们处理响应数据的时候,设置响应头
-
优化方案
- 根据不同的文件后缀设置不同的响应头
'Content-Type'
- 根据不同的文件后缀设置不同的响应头
3.4、优化静态资源服务器
-
脚本代码
// 提供一个http 服务 const http = require('http'); // fs 模块 用于读取文件的 const fs = require('fs') // 处理 url const path = require('path') const requestType = { ".css" : "text/css", ".js" : "text/javascript", ".html":"text/html", ".png":"image/png" }; // 创建一个服务 const server = http.createServer((request,response)=>{ let pathname = request.url //先获取地址 pathname=pathname=='/'?'/index.html':pathname //根目录下定位到首页 let ext = path.extname(pathname) // 获取资源后缀 fs.readFile('.' + pathname, (err,data)=>{ if (err) { response.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' }); response.end('<h3>404</h3>'); } else { response.writeHead(200, { 'Content-Type': `${requestType[ext]};charset="utf-8"` }); response.end(data); } } ) }) server.listen(9999)
-
效果
- 访问下图片看看
- 至此,我们的基础版静态资源服务器就搭建完成
4.0、express实现
- 脚本代码
var express = require('express'); var app = express(); app.use(express.static('./',{index:'index.html'})) app.listen(9999, function() { console.log("server start::http://localhost:9999"); });