根据服务器请求不同的地址响应得到的内容及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---')
})