当前位置: 首页 > 知识库问答 >
问题:

这个代码中缺少什么东西吗?我无法通过axios post请求进行发布

楚彦
2023-03-14

所以我设置了一个表单,用于获取用户详细信息并将数据设置为状态。然后我通过onSubmit函数将状态数据传递给数据库。我使用axios.post请求到本地主机服务器。我的获取请求似乎工作正常,但是提交表单后数据没有被张贴。

我的代码看起来像这样。(我正在提取不必要的代码。)

UserForm.jsx

class UserForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
      contact: "",
      company: "",
      mail: "",
      key: {
        wedding: false,
        MICE: false,
        corporate: false
      },
      app_no: "",
      items: "",
      isLoaded: false
    };
  }

handleSubmit = e => {
    console.log("Submitted");
    e.preventDefault();
    const users = {
      name: this.state.name,
      contact: this.state.contact,
      company: this.state.company,
      mail: this.state.mail,
      key: this.state.key,
      app_no: this.state.app_no
    };
    axios
      .post(
        "http://localhost:5000/api/items",
        { users },
        {
          headers: {
            "content-type": "application/json"
          }
        }
      )

      .then(console.log("Axios post is working"))
      .then(res => {
        console.log("Something: " + res);
        console.log(res.data);
      })
      .catch(err => {
        console.log(err);
      });
    console.log("Users; " + users.name);
  };


componentDidMount() {
    fetch("http://localhost:5000/api/items/", {
      headers: {
        "content-type": "application/json"
      }
    })
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          items: json
        });
      });
    console.log(this.state.items);
  }
const express = require("express");
const router = express.Router();

// Item model
const Item = require("../../models/Item");

// Routes
// @get API item get all items
// make a get req
router.get("/", (req, res) => {
  Item.find().then(items => res.json(items));
});

// @get Api item POST all items
// make a post req
// create an item
router.post("/", (req, res) => {
  const newItem = new Item({
    name: req.body.name,
    contact_no: req.body.contact_no,
    company_name: req.body.company_name,
    key: req.body.key
  });

  newItem.save().then(item => res.json(item));
});

// @del api item.
// delete request
router.delete("/:id", (req, res) => {
  Item.findById(req.params.id)
    .then(item => item.remove().then(() => res.json({ success: true })))
    .catch(err => res.status(404).json({ success: false }));
});

module.exports = router;

代码中有我遗漏的东西吗。我已经阅读了大部分axios文档,似乎没有发现问题。

server.js
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");

const app = express();
const items = require("./routes/api/items"); // Contains all the api routes

// Body Parser middleware
app.use(bodyParser.json());

// DB config
const db = require("./config/keys").mongoURI;

mongoose
  .connect(db, { useNewUrlParser: true })
  .then(() => console.log("Mongo is laoded"))
  .catch(err => console.log(err));

app.use("/api/items", items); // redirecting api routes to items

const port = process.env.PORT || 5000;

app.listen(port, () => console.log("Server started"));

让我知道,如果我应该发布更多的代码...编辑:我没有得到“console.log(”东西:“res);console.log(res.data);”控制台上的响应。我的控制台打印:

(2) [{…}, {…}]
Submitted
UserForm.jsx:56 Axios post is working
UserForm.jsx:70 Users; someuser

共有2个答案

南门鸿哲
2023-03-14

试试这个:

.then((res) => {
console.log("Axios post is working")
console.log("Something: " + res);
console.log(res.data);
})
沈健
2023-03-14

我不相信你能通过req.body.name获取你的记录,因为你的POST请求似乎把它放在req.body.users.name下,所以基本上你想从获取你的数据>req.body.users

 类似资料:
  • 我越来越熟悉Java使用Jax-ws(或JAXB,不确定,反正...)的网络服务。 我用一个单一的网络服务创建了一个小项目。WS有唯一的endpoint,称为传输,并返回继承ITransferResult接口的对象。 Web服务合同 Web服务实现 转让结果合同 转移结果实现 当我发布我的Web服务时,我得到以下错误: 异常线程"main"javax.xml.ws.WebServiceExctur

  • 我的代码基于SpringBoot,接收post请求,解析json数据并使用jdbc执行。 } curl命令如下所示: 但是,当我通过curl发送post请求时,无法解析参数并且始终为空。 为什么会发生这个问题,如何解决? 堆栈跟踪:

  • 问题内容: 通过AJAX进行MVC模型绑定时遇到一些麻烦。 谁能告诉我为什么CreateTransfereeDetails属性没有绑定,它总是返回为“ null”。 模型: HTML: JavaScript: 谢谢! 问题答案: 用于表单内的输入字段。自动分配给模型的属性。 并使用jquery的serialize()函数使用ajax传递数据

  • 我正在使用swig 4.0.2生成一个供tcl使用的包。 消息来源。i文件包含很多类和生成的_wrap。cpp文件包含了我所期望的所有类及其方法,并且一切编译正常,没有任何警告。 但是,对于至少一个类,当我从tcl脚本调用实例上的方法时,我会收到一个运行时错误,说该方法不存在。该错误还转储了该类的所有可用方法。我试图调用的方法以及其他一些方法不存在于该列表中。 虽然缺少哪些方法是一致的,但列表中似

  • 问题内容: 嗨,我是Android编程的新手,我想问的问题可能很简单,但是我对如何使其工作一无所知,请多多包涵。 我从Android开发人员网站安装了android-sdk和相关工具。我按照他们的指示创建了HelloWorld应用,但出现了一些我不理解的错误。 文件MainActivity.java是一个自动生成的文件,在以下位置,我不断出现此文件错误: 因此,我尝试浏览生成的class文件中的l

  • 问题内容: 我需要一种更快的方式来存储和访问大约3GB的线对。其中a或an和is可以具有不同的形状。是否有任何对象在存储和访问此类表方面比标准python dict快?例如,? 据我所知,python dict是哈希表的一种非常快速的实现,有什么比我的特定情况更好的方法吗? 问题答案: 不,没有比字典更快的速度了,这是因为其索引甚至成员资格检查的复杂度约为O(1)。 将项目保存在字典中后,您就可以