如何用服务器根据输入的路径读取html内容
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;
if (pathname === '/') {
pathname = '/default.html'
}
const 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=utf8'
})
res.end('文件读取失败');
return;
}
res.writeHead(200, {
'content-type': type
})
res.end(result)
})
})