javascript - 如何在单击带有 Node.js 和 HTML 的按钮时发送带有特定 URL 的 POST 请求?
问题描述
我正在尝试将 HTML 和 Vanilla JS 与 Node.js 一起使用,通过单击 HTML 按钮将一个字符串发送到我的文件,如果我使用“/jokes”的 url,它将在我的文件中附加一个POST request
字符串。server.js
jokes.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 文件位于同一文件夹中。提前致谢。
解决方案
推荐阅读
- python - Python 调度持久化
- python - PyTorch autograd -- 只能为标量输出隐式创建 grad
- wordpress - 向事件日历插件添加自定义功能
- php - 解析由 php 文件回显的 json 对象不起作用
- java - 如何在 Kotlin 或 Java 中对排序列表进行设置操作?
- asp.net - ASP.NET 和 Google Oauth 2 停止工作
- php - Prestashop 1.7 带有页眉和页脚的设置模板
- php - PHP 为全局变量返回 NULL
- android - 如何保存 Uri 表单图像?
- php - PHP cURL 正文不适用于多个数组