首页 > 解决方案 > 如何在单击带有 Node.js 和 HTML 的按钮时发送带有特定 URL 的 POST 请求?

问题描述

我正在尝试将 HTML 和 Vanilla JS 与 Node.js 一起使用,通过单击 HTML 按钮将一个字符串发送到我的文件,如果我使用“/jokes”的 url,它将在我的文件中附加一个POST request字符串。server.jsjokes.txt

这是我的index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Node.js Joke App</title>
</head>
<body>
    <button class="add-joke">Add Joke</button>
    <script src="client.js"></script>
</body>
</html>

这是我的client.js

document.getElementById("add-joke").addEventListener("click", () => {
    const data =
        "Why did the chicken cross the road? To get to the other side.";

    const options = {
        hostname: "127.0.0.1",
        port: 3000,
        path: "/jokes",
        method: "POST",
        headers: {},
    };

    const req = request(options, (res) => {
        console.log(`statusCode: ${res.statusCode}`);

        res.on("data", (d) => {
            process.stdout.write(d);
        });
    });

    req.on("error", (error) => {
        console.error(error);
    });

    req.write(data);
    req.end();
});

这是我的 server.js

const http = require("http");
const fs = require("fs");

const hostname = "127.0.0.1";
const port = 3000;
const server = http.createServer((req, res) => {
    const { method, url } = req;
    res.statusCode = 200;
    res.setHeader("Content-type", "text/html");

    if (url === "/") {
        fs.readFile("./index.html", null, function (error, data) {
            if (error) {
                res.writeHead(404);
                res.write("File not found");
            } else {
                res.write(data);
            }
            res.end();
        });
    } else if (url === "/jokes" && method === "POST") {
        writeFile("./jokes.txt"), `${req.data}`, { flag: "a" };
    } else {
        res.write("DOES NOT EXIST!");
    }

    res.end();
});

server.listen(port, hostname, () => {
    console.log(`Server running at ${hostname}:${port}`);
});

我没有收到任何错误,但我的 index.html 文件甚至没有出现在127.0.0.1:3000. 它是空白的空白,控制台没有显示错误。我不确定我做错了什么。我的 index.html 文件与我的 server.js 文件位于同一文件夹中。提前致谢。

标签: javascripthtmlnode.js

解决方案


推荐阅读