express搭建服务器
step0: node http模块的代码实例讲解
const http = require("http");
const server = http.createServer((request, response) => {
setTimeout(_ => {
// 设置返回到浏览的解析类型 这里设置的charset优先级大于页面中meta中charset优先级
response.setHeader("content-type", "text/html;charset=gbk");
// 设置返回码
response.writeHead(404, 'Not Found');
// 返回值
response.write('<html><head><meta charset="gbk" /></head>')
response.write('<body>')
response.write('<h1>你好</h1>')
response.write('</body>')
response.write('</html>')
// 返回值写完之后需要使用 end()方法结束
response.end();
}, 2000)
})
console.log('open http://localhost:8080')
// 服务器监听localhost:8080端口
server.listen(8080);
访问http://localhost:8080端口返回值:
step1: 搭建静态服务器
实例及结果返回:
const http = require("http");
const fs = require("fs");
const url = require("url");
const path = require("path");
function staticRoot(staticPath, req, res) {
// 解析传过来的url端口后面的 url地址及参数字符串
console.log(req.url);
// 将req.url 解析为一个对象 里面的pathname就是裸的url地址
let pathObj = url.parse(req.url);
console.log(pathObj);
// 如果地址是单纯的/ 那么浏览器打开/index.html
if(pathObj.pathname === "/"){
pathObj.pathname += "index.html";
}
// 拼接请求的资源路径
let filePath = path.join(staticPath, pathObj.pathname);
// 读取filePath 地址下面的资源() binary为二进制读取
fs.readFile(filePath, "binary", (err, fileContnet) => {
// 如果读取的文件不存在 那么返回状态码为404 状态信息为 Not Found
if(err) {
console.log(404);
res.writeHead("404", "Not Found");
res.end("<h1>404 Not Found</h1>");
} else {
// 文件读取成功 返回状态码为200 状态信息是 success
res.writeHead("200", "success");
// 返回 二进制的信息 展示到浏览器中
res.end(fileContnet);
}
})
}
const server = http.createServer((req, res) => {
console.log(__dirname);
console.log(path.join(__dirname, "static"))
staticRoot(path.join(__dirname, "static"), req, res);
});
server.listen(8080);
console.log("http://localhosthost:8080");
注意: 如果不设置文件的解析类型,浏览器根据文件后缀名来解析文件。
step2: 路由解析,访问的是文件走读取文件函数,访问的是接口,返回相应接口参数
const fs = require("fs");
const path = require("path");
const http = require("http");
const url = require("url");
// 接口路由
let routes = {
"/a": (req, res) => {
res.write("match /a\n");
res.end(JSON.stringify(req.query));
},
"/b": (req, res) => {
res.write("match \b");
res.end(JSON.stringify(req.query));
},
"/a/b": (req, res) => {
res.write("match /a/b\n");
res.end(JSON.stringify(req.query));
}
}
let server = http.createServer((req, res) => {
let pathObj = url.parse(req.url);
console.log(pathObj.pathname);
let handleFn = routes[pathObj.pathname];
console.log(handleFn);
// 如果是访问的接口地址
if(handleFn) {
req.query = ParseBody(pathObj.query);
console.log(req.query);
let body = "";
// post请求及get请求封装返回值
req.on("data", chunk => {
body += chunk;
console.log(body);
}).on("end", _ => {
// console.log(body);
req.body = ParseBody(body);
handleFn(req, res);
})
} else {
// 如果访问的不是接口地址 访问static下的文件
retRes(req, res);
}
})
// 封装"name=12&age=18" 转换为对象 {name: 12, age: 18}的函数
function ParseBody(body) {
body = body || "";
let bodyToObj = {};
body.split("&").forEach(item => {
console.log(1111);
console.log(item);
bodyToObj[item.split("=")[0]] = item.split("=")[1];
});
console.log(body);
console.log(bodyToObj);
return bodyToObj;
}
// 如果访问的不是接口地址 访问static下的文件
function retRes( req, res) {
let pathName = url.parse(req.url).pathname;
if(pathName === "/") {
pathName = "index.html"
}
let wholeFilePath = path.join(__dirname, "static/", pathName);
console.log(wholeFilePath);
fs.readFile(wholeFilePath, (err, fileContent) => {
if(err) {
res.writeHead("503", "nice");
res.end("503 服务器拒绝访问");
} else {
res.writeHead("200", "nice");
res.end(fileContent);
}
})
}
server.listen(8080)
console.log("http://localhosthost:8080");