//创建网站服务器的模块
const http = require('http')
const path = require('path')
const fs = require('fs')
const url= require('url')
//mime模块可以根据当前的请求路径,分析出资源类型来,设计出类型
const mime = require('mime')
//处理请求参数模块
const querystring = require('querystring')
//app是网站服务器对象
const app = http.createServer()
app.on('request',(req,res)=>{
const method = req.method.toLowerCase();
let {pathname} = url.parse(req.url,true)
pathname = pathname == '/'?'/index.html':pathname
let realPath = path.join(__dirname,'public'+pathname)
let type = mime.getType(realPath); //根据路径获取文件类型;高级浏览器中不用
fs.readFile(realPath,(error,result)=>{
if(error != null){
res.writeHead(404,{
'content-type':'text/html;charset=utf-8'
})
res.end('文件读取失败')
return;
}
res.writeHead(200,{
'content-type':type
})
res.end(result)
})
});
app.listen(3000)
console.log('网站服务器启动成功')
【nodejs】nodejs创建服务器并且返回静态资源(7)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.