美文网首页
Node.js_后端路由(一)

Node.js_后端路由(一)

作者: learninginto | 来源:发表于2020-03-01 00:11 被阅读0次

    Node.js_后端路由(一)

    路由指的就是我们要针对不同的URL有不同的处理方式。

    • JS在处理URL时,req.url中的pathname就是用户请求的路径,query就是get请求时用户传递的参数。所以说pathname就是路由的核心

      req.url.png
    • 读取服务端的文件时,需要通过content-type反馈给客户端,告诉它读取的文件是什么类型的。

      例如:

      res.writeHead(200, { "contentType": "text/html;charset=utf8" });

      res.writeHead(200, { "content-type": "application/x-javascript;charset=utf8" });

      res.writeHead(200, { "content-Type": "application/JSON;charset=utf-8" })

    • 请求图片时,使用正则表达式的子匹配项来区分请求的图片名和后缀。

      if (/\/img\/(.*)\.(jpg|png|gif)/.test(pathname)) {
          fs.readFile(path.join(__dirname, "./public/img/" + RegExp.$1 + "." + RegExp.$2), (err, data) => {
              res.writeHead(200, { "content-type": "image/" + RegExp.$2 });
              res.end(data);
          })
      
    • 测试数据存放在json文件中

      json数据.png
    • 登录注册的node代码

    const http = require("http");
    const path = require("path");
    const fs = require("fs");
    const url = require("url");
    const server = http.createServer((req, res) => {
        // console.log(url.parse(req.url, true))
        const { pathname, query } = url.parse(req.url, true);
    
        if (pathname === "/") {
    
            fs.readFile(path.join(__dirname, "./public/index.html"), (err, data) => {
                res.writeHead(200, { "contentType": "text/html;charset=utf8" });
                res.end(data);
            })
    
        } else if (pathname === "/order") {
            fs.readFile(path.join(__dirname, "./public/html/order.html"), (err, data) => {
                res.writeHead(200, { "contentType": "text/html;charset=utf8" });
                res.end(data);
            })
        } else if (pathname === "/list") {
            fs.readFile(path.join(__dirname, "./public/html/list.html"), (err, data) => {
                res.writeHead(200, { "contentType": "text/html;charset=utf8" });
                res.end(data);
            })
        } else if (/\/css\/(.*)\.css/.test(pathname)) {
            fs.readFile(path.join(__dirname, "./public/css/" + RegExp.$1 + ".css"), (err, data) => {
                res.writeHead(200, { "content-type": "text/css;charset=utf8" });
                res.end(data);
            })
        } else if (/\/js\/(.*)\.js/.test(pathname)) {
            fs.readFile(path.join(__dirname, "./public/js/" + RegExp.$1 + ".js"), (err, data) => {
                res.writeHead(200, { "content-type": "application/x-javascript;charset=utf8" });
                res.end(data);
            })
        } else if (/\/img\/(.*)\.(jpg|png|gif)/.test(pathname)) {
            fs.readFile(path.join(__dirname, "./public/img/" + RegExp.$1 + "." + RegExp.$2), (err, data) => {
                res.writeHead(200, { "content-type": "image/" + RegExp.$2 });
                res.end(data);
            })
        } else if (pathname === "/users/register") {
            let { username, password } = query;
            fs.readFile(path.join(__dirname, "./public/data/user.json"), (err, data) => {
                let userData = JSON.parse(data.toString());
                var bStop = true;
    
                for (var i = 0; i < userData.data.length; i++) {
                    if (userData.data[i].username === username) {
                        bStop = false;
                        break;
                    }
                }
                if (bStop) {
                    userData.data.push({ username, password });
                    fs.writeFile(path.join(__dirname, "./public/data/user.json"), JSON.stringify(userData), (err) => {
                        if (!err) {
                            res.writeHead(200, { "content-Type": "application/json;charset=utf-8" })
                            res.end(JSON.stringify({
                                code: 200,
                                errMsg: "",
                                data: {
                                    code: 1,
                                    info: "注册成功"
                                }
                            }))
                        }
                    })
                } else {
                    res.writeHead(200, { "content-Type": "application/json;charset=utf-8" })
                    res.end(JSON.stringify({
                        code: 200,
                        errMsg: "",
                        data: {
                            code: 0,
                            info: "用户名重复"
                        }
                    }))
                }
            })
        }
        else if (pathname === "/users/login") {
            let { username, password } = query;
            var resObj = {
                code: 200,
                errMsg: ""
            }
            fs.readFile(path.join(__dirname, "./public/data/user.json"), (err, data) => {
                let userData = JSON.parse(data.toString());
                var loginStop = 0;
                for (var i = 0; i < userData.data.length; i++) {
                    if (userData.data[i].username === username) {
                        loginStop = 2;
                        if (userData.data[i].password === password) {
                            loginStop = 1;
                            break;
                        }
                    }
                }
                res.writeHead(200, { "content-Type": "application/JSON;charset=utf-8" })
                if (loginStop === 1) {
                    // userData.data.push({ username, password });
                    resObj.data = {
                        code: 1,
                        info: "登录成功,跳转主页!"
                    }
                } else if (loginStop === 2) {
                    resObj.data = {
                        code: 0,
                        info: "用户密码错误!"
                    }
                } else {
                    resObj.data = {
                        code: 0,
                        info: "用户不存在!"
                    }
                }
                res.end(JSON.stringify(resObj))
            })
        }
    })
    
    server.listen(9000, () => {
        console.log("server address:127.0.0.1:9000")
    })
    

    相关文章

      网友评论

          本文标题:Node.js_后端路由(一)

          本文链接:https://www.haomeiwen.com/subject/dednhhtx.html