服务器端不需要处理,可以直接响应给客户端的资源就是静态资源,例如CSS、JavaScript、image文件。
const http = require("http")
const url = require("url")
const path = require("path")
const fs = require("fs")
const mime = require("mime")
const app = http.createServer()
app.on('request',(req,res)=>{
let { pathname } = url.parse(req.url);
pathname = pathname == '/' ? 'default.html' : pathname;
let finlurl = path.join(__dirname,'public',pathname);
// 读取文件
fs.readFile(finlurl,(err,result)=>{
if(err != null){
res.writeHead(404,{
"content-type":'text/html;charset=utf8'
});
res.end('读取失败');
return;
}
let type = mime.getType(finlurl);
res.writeHead(200,{
"content-type": type
})
res.end(result);
});
});
app.listen(3000);
console.log("服务器已经启动...");