//静态资源访问 const http = require('http'); const url = require('url'); const path = require('path'); const fs = require('fs'); //mime这个第三方模块的功能是根据当前的请求路径,分析出这个资源的类型,通过返回值的方式返回资源类型。 const mime = require('mime'); const app = http.createServer(); //监听服务器 app.on('request',(req,res)=>{ //获取用户请求路径 let pathname = url.parse(req.url).pathname pathname = pathname =='/'? '/index.html': pathname //将用户的请求路径转换为实际的服务器硬盘路径 let realpath = path.join(__dirname,'public'+pathname) console.log(realpath) let type = mime.getType(realpath) // console.log(type); fs.readFile(realpath,(error,result)=>{ if(error != null){ res.writeHead(404,{ 'content-type':'text/html;charset=utf8' }) res.end('文件读取失败') return; } res.writeHead(200,{ 'content-type' : type }) res.end(result) }) }); app.listen(80); console.log('服务器启动成功!')
版权声明:
本文来源网络,所有图片文章版权属于原作者,如有侵权,联系删除。
本文网址:https://www.mushiming.com/mjsbk/10329.html