我最近开始使用 Express 框架学习 Node.js。我创建了一个简单的服务器,并附加了一个 HTML 文件,其中包含一个表单,该表单由一个提交类型的按钮组成,该按钮应该向服务器发送一个发布请求。它没有给我任何错误,但是当我尝试在按下提交按钮时将消息记录到控制台时,什么也没有发生。我很确定它与 HTML 表单语法有关,但我永远不能太确定。这是 HTML:
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<form class="test" action="http://localhost:8000/example" method="post">
<input type="submit" name="but" value="Press me">
</form>
</body>
</html>
这里是快速代码:
const http = require("http");
const app = require("express")();
const path = require('path');
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/example", (req, res) => {
console.log("pressed");
});
app.listen(8000, ()=>{
console.log("Running at 8000");
});
最佳答案
发生这种情况是因为 app.use ()
被视为应用程序的中间件。为了正常工作,您应该使用app.get()
。 Here是更详细的解释。另一种选择是提供您的 html 作为静态内容,您可以查看有关 here 的更多信息。 .
为了正常工作,您应该将代码更改为:
app.get("/", (req, res) => {
res.sendFile(__ dirname + "/index.html");
});
您还可以将 HTML 修改为:
<form class="test" action="/example" method="post">
因为是在同一个主机上。当对其他主机执行操作时,您只需使用完整的 url。
关于javascript - 在 Express 中接收 POST 请求时登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61105167/