• 08-Node.js学习笔记-静态资源访问


    静态资源

    服务器端不需要处理,可以直接响应给客户端的资源就是静态资源,例如css,javaScript,image文件

    动态资源

    相同的请求地址不同的响应资源,这种资源就是动态资源

    ``` http://www.xxx.cn/article?id=1 http://www.xxx.cn/article?id=2 ```

    第三方模块mime下载

    ``` //mime插件:可以根据当前的请求路径分析出资源的类型,然后把类型通过返回值的方式返回给你 npm install mime ``` ``` 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=pathname=='/'?'/cc.html':pathname; //将用户的请求路径转换为实际的服务器硬盘路径 let realPath = path.join(__dirname,'public'+pathname); let type=mime.getType(realPath) //读取文件 fs.readFile(realPath,(err,result)=>{ //如果文件读取失败 if(err !=null){ res.writeHead(404,{ 'content-type':'text/html;charset=utf8' }) res.end('文件读取失败'); return; } res.writeHead(200,{ 'content-type':type }) res.end(result)
    })
    

    })
    app.listen(3000);
    console.log('服务器启动成功')

  • 相关阅读:
    1029 旧键盘 (20 分)
    1028 人口普查 (20 分)
    1026 程序运行时间 (15 分
    1025 反转链表 (25 分
    1024 科学计数法 (20 分
    1023 组个最小数 (20 分)
    将命令的输出保存到文件
    使用与管理控制台历史
    度量命令执行时间
    检查最后运行命令的状态
  • 原文地址:https://www.cnblogs.com/foreverLuckyStar/p/12072123.html
Copyright © 2020-2023  润新知