首页 > 解决方案 > 使用 Axios 的 POST 方法只在数据库中插入 ID。反应 JS

问题描述

我正在尝试在 React 中使用 Axios 发出 POST 请求。显然没有问题,因为返回的状态是 200“OK”,但只有 ID 被插入到数据库中。我正在使用以下代码段来执行请求:

  handleSubmit = async (e) => {
e.preventDefault();

axios.defaults.baseURL = "http://localhost:8000";

try {
  console.log(this.state.form);
  const response = await axios.post("/create", this.state.form);
  console.log(response);
} catch (error) {
  console.error(error);
}

};

我在Postman中测试了一下,好像没有问题。 在 Postman 中测试

但是当我试图从前端创建一个新的寄存器时,只在数据库中插入 ID。也许这张照片可能有用。 控制台中的响应

标签: javascriptreactjsapi

解决方案


axios.post("/create", this.state.form)您所做的不等同于邮递员请求

在 Postman 请求中,您将参数添加为url 参数 并在 Axios 请求中作为正文参数发送

所以你需要做的是像这样发送 Axios 请求:

await axios.post(`/create?firstname=${this.state.form.firstname}&lastname=${this.state.form.lastname}&salary=${this.state.form.salary}`,{});

如果没有,那应该对您有用-添加服务器路由器代码


推荐阅读