zoukankan      html  css  js  c++  java
  • 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('服务器启动成功')

  • 相关阅读:
    TreeSet介绍
    ArrayList中元素去重问题
    SpringMVC + Spring + Mybatis + Maven整合实例
    CXF整合Spring发布WebService实例
    使用CXF发布WebService服务简单实例
    Struts2文件下载
    Axis2在Web项目中整合Spring
    Struts2防止表单重复提交
    Axis2与Web项目整合
    使用Axis2实现WebService的发布和调用
  • 原文地址:https://www.cnblogs.com/foreverLuckyStar/p/12072123.html
Copyright © 2011-2022 走看看