node-server之express

1 篇文章 0 订阅
1 篇文章 0 订阅

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");

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值