我正在开发一个使用react-hook-form的表单,而提交所有的细节,我面临404错误。下面是服务器端代码:
const express = require("express");
const mysql = require("mysql");
const cors = require("cors");
const bodyParser = require("body-parser");
const app = express();
app.use(cors());
app.use(bodyParser.json());
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "1234",
database: "registration",
});
connection.connect((err) => {
if (err) throw err;
console.log("Connected to MySQL Database");
});
app.post("/users", async (req, res) => {
const formData = req.body;
const sql = "INSERT INTO users SET ?";
connection.query(sql, formData, (err, result) => {
if (err) throw err;
console.log(result);
res.send("User registered successfully");
});
});
app.get("/api/users", (req, res) => {
const sql = "SELECT * from users";
connection.query(sql, (err, result) => {
if (err) throw err;
console.log(result);
res.send(result);
});
});
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port}`));
下面是客户端代码:
const onSubmithandler = (data) => {
axios
.post("http://localhost:5000/users", data)
.then((response) => {
console.log(response.data);
reset();
setMessage("User registered successfully");
})
.catch((error) => console.log(error));
};
我试过用axios和async,await开发,但它产生了同样的错误。
1条答案
按热度按时间ryevplcw1#
您需要告诉请求请求是
localhost
,需要添加localhost
到post url如果你已经通过
app.use('/api/v1', ...)
或类似的方式声明了app,那么你还需要将它附加到你的url中,比如http://localhost:YOUR_PORT/api/v1/user/register