NodeJS AxiosError {message:“请求失败,状态代码为404”,名称:'AxiosError',代码:'ERR_BAD_REQUEST'

zphenhs4  于 2023-04-29  发布在  Node.js
关注(0)|答案(1)|浏览(86)

我正在开发一个使用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开发,但它产生了同样的错误。

ryevplcw

ryevplcw1#

您需要告诉请求请求是localhost,需要添加localhost到post url

const onSubmithandler = (data) => {
    axios
      .post("http://localhost:YOUR_PORT/user/register", data)
      .then((response) => {
        console.log(response.data);
        reset();
        setMessage("User registered successfully");
      })
      .catch((error) => console.log(error));
  };

如果你已经通过app.use('/api/v1', ...)或类似的方式声明了app,那么你还需要将它附加到你的url中,比如
http://localhost:YOUR_PORT/api/v1/user/register

相关问题