分享

node.js静态资源访问

 精品唯居 2021-09-08
 1 const http = require('http');
 2 const url = require('url');
 3 const path = require('path');
 4 const fs = require('fs');
 5 const mime=require('mime');
 6 
 7 
 8 const app = http.createServer();
 9 app.on('request',(req,res)=>{
10 
11     //获取用户请求路劲
12     let pathname=url.parse(req.url).pathname;
13 
14     pathname = pathname== '/'? '/default.html':pathname;
15     //将用户的请求路径转换为实际的服务器路径
16     let realPath=path.join(__dirname,'public'+pathname);
17 
18     // 当前请求文件类型
19     // console.log(mime.getType(realPath)); 
20     let type = mime.getType(realPath);
21     //读取文件
22     fs.readFile(realPath, (error,result)=>{
23         if(error != null){
24             res.writeHead(400, {
25                 'content-type': 'text/html;charset=utf8'
26             });
27             res.end('文件读取失败');
28             return;
29         }
30         res.writeHead(200,{
31             'content-type':type
32         })
33         res.end(result)
34     })
35 })
36 
37 app.listen(3000);
38 console.log('服务器启动成功');

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多