NODEJS[27]:http模块_完善错误处理
·
Yin灏
const http = require("http");
const fs = require("fs");
const path = require("path");
let mimes = {
html: "text/html",
css: "text/css",
js: "text/javascript",
png: "image/png",
jpg: "image/jpeg",
git: "image/gif",
mp4: "video/mp4",
mp3: "audio/mp3",
json: "application/json",
};
const server = http.createServer((request, response) => {
if (request.method !== "GET") {
response.statusCode = 405;
response.end("<h1>405 Method Not Allowed</h1>");
return;
}
let { pathname } = new URL(request.url, "http://127.0.0.1");
let filePath = __dirname + "/page" + pathname;
fs.readFile(filePath, (err, data) => {
if (err) {
response.setHeader("content-type", "text/html;charset=utf-8");
switch (err.code) {
case "ENOENT":
response.statusCode = 404;
response.end("<h1>404 Not Found</h1>");
case "EPERM":
response.statusCode = 403;
response.end("<h1>403 Forbidden</h1>");
default:
response.statusCode = 500;
response.end("<h1>Internal Server Error</h1>");
}
return;
}
let ext = path.extname(filePath).slice(1);
response.setHeader(
"content-type",
mimes[ext] || "application/octet-stream" + ";charset=utf-8"
);
response.end(data);
});
});
server.listen(9000, () => {
cons.log("服务器已经启动了...");
});