同步重新写入和结束

时间:2019-07-15 15:09:27

标签: node.js

我大约有3条路线,我用if / else if / else划分。

在所有这些if语句后面都加了res.end(),因为我不想在所有事情后面都放它。

所以在if语句中我只是写。

但是有时res.end在if语句结束之前执行。这意味着它什么都不写。

我该如何解决?

const http = require("http");

const postDataToJson = require("./post-data-to-json.js");

const {
    PORT = 8080
} = process.env

const users = {
    username: "Radka",
    password: 1234
}

function makeID() {
    let result = "";
    let characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    let charactersLength = characters.length;
    for(let i = 0; i < 8; i++ ) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
}

let sessionID;

const server = async (req, res) => {
    if(req.url == "/" && req.method === "GET") {
        res.writeHead(200, {
            "Content-Type": "text/html; charset=utf-8"
        });
        res.write(`
            <h1>Main</h1>
            <form method="POST" action="/login">
                <input type="text" name="username">
                <br>
                <input type="text" name="password">
                <br>
                <input type="submit">
            </form>
        `);
    } else if(req.url == "/login" && req.method === "POST") {
        let postData = "";

        req.on("data", (chunk) => {
            postData += chunk.toString();
        });

        req.on("end", () => {
            postData = postDataToJson(postData);

            if(postData["username"] == users.username && postData["password"] == users.password) {
                sessionID = makeID();
                res.writeHead(302, {
                    "Location": "/dashboard"
                })
            } else {
                res.writeHead(301, {
                    Location: "/"
                });
            }
        });
    } else if(req.url == "/dashboard" && req.method === "GET") {
        if(sessionID) {
            res.write(`
                <h1>Dashboard</h1>
            `);
        } else {
            res.writeHead(302, {
                Location: "/"
            });
        }
    } else {
        res.writeHead(404);
        res.write("File not found.");
    }
    res.end();
}

http.createServer(server).listen(PORT);

0 个答案:

没有答案