关于node服务器响应静态资源时Content-Type所对应的不同的文件格式匹配,以及对响应静态资源的封装一个方法

根据服务器请求不同的地址响应得到的内容及Content-Type的不同类型的鉴别;

根据请求不同的文件格式获取对应文件的后缀,然后进行判断;如果Content-Type:以text开头的要设置编码格式utf8

 

 /*
    响应完整的页面信息
 */

const http = require('http');
const path = require('path');
const fs = require('fs');
const mime = require('./mime.json')  //各种文件的后缀映射关系json

http.createServer((req,res) => {
 fs.readFile(path.join(__dirname,'www',req.url),(err,fileContent) => {
   if(err){
     //没有找到对应的文件
     res.writeHead(404,{
       'Content-Type':'text/plain; chartset=utf8'
     });
     res.end('你访问的页面不存在!');
   }else{
    let dtype = 'text/html';
    //获取请求文件的后缀
    let ext = path.extname(req.url);
    //如果请求的文件后缀合理,就获取到标准的响应格式
    if(mime[ext]){
      dtype = mime[ext]
    }
    //如果响应的内容是文本,就设置utf8
    if(dtype.startsWith('txet')){
      dtype += '; chartset=utf8'
    }
    res.writeHead(200,{
      'Content-Type':dtype
    });
    res.end(fileContent)
   }
 })
}).listen(3000,() => {
  console.log('running----')
})

 下面对上面的代码封装,下次使用直接导入使用:

 


const path = require('path');
const fs = require('fs');
const mime = require('./mime.json')  //各种文件的后缀映射关系json


exports.staticServer = (req,res,root) => {
  fs.readFile(path.join(root,req.url),(err,fileContent) => {
    if(err){
      //没有找到对应的文件
      res.writeHead(404,{
        'Content-Type':'text/plain; chartset=utf8'
      });
      res.end('你访问的页面不存在!');
    }else{
     let dtype = 'text/html';
     //获取请求文件的后缀
     let ext = path.extname(req.url);
     //如果请求的文件后缀合理,就获取到标准的响应格式
     if(mime[ext]){
       dtype = mime[ext]
     }
     //如果响应的内容是文本,就设置utf8
     if(dtype.startsWith('txet')){
       dtype += '; chartset=utf8'
     }
     res.writeHead(200,{
       'Content-Type':dtype
     });
     res.end(fileContent)
    }
  })
}

导入在另一个文件用: 

const path = require('path');
const http = require('http');
const ss = require('./08.js')

http.createServer((req,res) => {
  ss.staticServer(req,res,path.join(__dirname,'www'))
}).listen(3000,() => {
  console.log('running---')
})

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值