服務器端
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) => {
// /index - 首頁
// /about 關於我們
// /news 首頁
// 其他的 不存在
let { pathname } = url.parse(req.url); // /index
if (pathname === '/' || pathname === '/index') {
pathname = '/index.html';
}
let pathStr = path.join(__dirname, pathname);
// let a = path.join(__dirname, pathname);
// console.log(path.resolve(pathname));
let fileType = mime.getType(pathStr);
if (fileType === 'text/html') {
fs.readFile(pathStr, 'utf8', (err, data) => {
res.writeHead(200, {
'Content-Type': `${fileType};charset=utf8`
});
res.end(data);
});
} else if (fileType === 'text/css') {
res.writeHead(200, {
'Content-Type': `${fileType};charset=utf8`
});
fs.readFile(pathStr, 'utf8', (err, data) => {
res.end(data);
});
}
else if (fileType === 'image/jepg') {
// res.writeHead(200, {
// 'Content-Type': `${fileType}`
// });
fs.readFile(pathStr, 'utf8', (err, data) => {
res.end(data);
});
} else {
fs.readFile(pathStr, (err, data) => {
if (err !== null) {
res.writeHead(404, {
'Content-Type': 'text/html;charset=utf8'
});
res.end('頁面不存在');
}
res.writeHead(200, {
'Content-Type': `${fileType}`
});
res.end(data);
});
}
});
app.listen(9999);
console.log('已經啓動');
其他文檔