第一种
let express = require('express');
let app = express();
let path = require('path')
let fs = require('fs');
let mime = require('mime')
//设置跨域访问
app.all('*', (req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
// app.use('/static',express.static('static'));
app.use("/",(req, res)=>{
// console.log(req.path);
// 请求路径
let pathname = req.path
// 处理 / /index 都是读取 /index.html
if(pathname == '/' || pathname == '/index'){pathname = '/index.html'}
// 路径拼接 将用户的请求路径转换为实际的服务器硬盘路径
let readPath = path.join(__dirname + pathname)
// console.log(readPath)
// 根据路径返回资源的类型
let zy = mime.getType(readPath)
res.setHeader('Content-type',zy+";charset=utf-8")
fs.readFile(readPath, (err, data)=>{
if(err){
res.end("404")
return
}
res.end(data)
})
})
app.listen(4000,()=>{
console.log('http://localhost:4000')
})
我的目录结构

第二种
静态目录

网友评论