【问题标题】:How to GET the item just created by the POST如何获取 POST 刚刚创建的项目
【发布时间】:2021-07-07 22:51:42
【问题描述】:

我成功地通过 axios 获取数据,现在我需要通过刚刚通过 POST 方法创建的 axios 获取数据。这是我的代码:

  data() {
    return {
      showModal: false,
      info: null,
      percentage: 0,
      selected_item: {
        id: 0,
        bill_number: 0,
        date: "",
        user_id: 0,
      },
    };
  },
    getNewDeal() {
      axios.post("http://localhost:8080/bills", {
        bill_number: 108,
        date: "",
        user_id: 7,
      });
      axios
        .get("http://localhost:8080/bills")
        .then((response) => (this.info = response.data._embedded.bills));
      this.info[this.info.length - 1].id = this.selected_item.id;
      console.log(this.selected_item.id);
    },

console.log(this.selected_item.id);返回 0 它应该返回类似 69843 的内容,id 是自动生成的。

【问题讨论】:

    标签: javascript vue.js axios


    【解决方案1】:

    您的 POST api 调用应该创建项目,然后返回新创建项目的 ID。然后您可以执行以下操作。

    getNewDeal() {
        axios.post("http://localhost:8080/bills", {
          bill_number: 108,
          date: "",
          user_id: 7,
        }).then((response) => { // This response should have the ID of the newly created item, this should be set in the POST api call after item create.
          this.selected_item.id = response.data.id // I dont know your response object but get the ID from the response.
          axios
            .get("http://localhost:8080/bills")
            .then((response) => {
              this.info = response.data._embedded.bills;
              this.info[this.info.length - 1].id = this.selected_item.id;
              console.log(this.selected_item.id);
            });
        })
      }
    
    

    如果您只需要单行,我还认为您应该对单个项目进行 GET 调用。 http://localhost:8080/bills/{id}

    【讨论】:

    • 抱歉,我对响应 .id 所代表的内容有点陌生,因为我的 API 上的对象有 4 个值,id(自动生成)、bill_number、date 和 user_id。如果我尝试您给我的确切代码,它会在控制台日志中显示未定义。另外,我只会得到一件物品,但我不知道它的 id,所以我不知道要获取哪个 id。
    • 在发布请求后控制台日志响应会得到什么?
    • 我得到了整个对象,好像 POST 请求成功通过了!但是当我稍后打印 ID 时,它说它未定义。 ```数据:对象{ id:667005,bill_number:7,user_id:777777,...}```
    • 确切的响应中有对象文本吗?
    • 好的,我解决了,我需要在 id 之前添加数据,所以它是这样的 this.selected_item.id = response.data.id,编辑你的答案,以便我批准它,tnx!是的,响应中有更多对象,我只是复制了我认为有用的对象。
    猜你喜欢
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    相关资源
    最近更新 更多