当用户单击表单上的提交按钮时,我正在尝试将一些数据上传到学校数据库。我已经设置了 server.js,它可以与 Postman 一起使用。但是,当我尝试在单击按钮时获取(POST)数据时,我在浏览器控制台中收到 404 错误。
出于某种原因,如果服务器已经在运行,我也无法打开我的 html 文件。我不知道这是否相关。
我已经仔细检查了将客户端 fetch 和服务器端 app.post() 连接在一起的每个字符串。我还通过在 Postman 中使用相同的文本检查了从我的应用程序发送的 JSON 数据是否被接受。这行得通。我也尝试过查看类似的帖子,但没有人遇到完全相同的问题(据我所知)。
这是我的 server.js:
let express = require("express");
let mysql = require("mysql");
let bodyParser = require("body-parser");
let app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
let pool = mysql.createPool({
connectionLimit: 2,
host: "---",
user: "---",
password: "---",
database: "---",
debug: false
}
);
app.post("/send", (req, res) => {
console.log("Received Post from client");
pool.getConnection((err, connection) => {
if (err) {
console.log("Connection error");
res.json({ error: "connection error" });
} else {
console.log("Connection established");
console.log(req.body);
let val = [req.body.some_value];
console.log(val);
connection.query(
"insert into some_table (some_value) values (?)",
val,
err => {
if (err) {
console.log(err);
res.status(500);
res.json({error: "Insertion error"});
} else {
console.log("Insertion OK!");
res.send("");
}
}
);
}
});
});
let server = app.listen(8080);
console.log("Server running");
我的客户(sendButton.js):
document.getElementById("submit").addEventListener("click", function(){
let data = {some_value: document.getElementById("some_value_input")};
console.log(JSON.stringify(data));
fetch("http://localhost:8080/send", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(function(response){
alert("We're trying");
if (response.ok){
console.log("Data uploaded");
return;
}
throw new Error("Data not uploaded");
})
.catch(function(error){
console.log(error);
});
});
HTML 按钮只是一个标准按钮,其 id 为“提交”。
我的预期结果:插入正常,将值发送到数据库而没有错误。
实际结果:404 page not found 错误:
