【问题标题】:Get data by id using Axios and VueJS使用 Axios 和 VueJS 通过 id 获取数据
【发布时间】:2019-04-19 01:55:57
【问题描述】:

我的服务器端有这个 get 函数,我想通过将 ID 作为参数来获取数据库中的特定条目。在我的 VueJS 应用程序中,我编写了一个 Axios get-call,但它没有给我任何数据。它只说

“无法获取...”。

我知道我为函数提供的 ID 是正确的,所以这不是问题。

客户端

loadData() {
     axios.get('http://localhost:8080/route', {
        params: {
            id: this.selectedRoute
        }
     })
     .then(response => (this.chosenRoute = response.data));
}

服务器端

app.get('/route/:id', function(req, res) {
    const routeId = req.params.id;
    Route.findById(routeId, (err, route) => {
        res.set("Access-Control-Allow-Origin", "*");
        res.json(route);
    });
});
    enter code here

【问题讨论】:

    标签: javascript typescript vue.js vuejs2 axios


    【解决方案1】:

    通过将id(即this.selectedRoute)连接到url 来尝试类似的操作:

      loadData() {
         axios.get('http://localhost:8080/route/'+ this.selectedRoute)
                  .then(response => (this.chosenRoute = response.data));
    }
    

    在你的最后一个问题中,你有这个:

          <select name="routeSelect" v-model="selectedRoute">
              <option v-for="routes in result" v-bind:key="routes.name" v- 
               bind:value="routes.name"> {{ routes.name }} </option>
          </select>
    

    这不起作用,因为 selectedRoute 是路线 name 不是 id 来解决你必须这样做:

              <option v-for="routes in result" v-bind:key="routes.name" v- 
               bind:value="routes.id" >...
    

    通过将选择选项 value 绑定到 路由 id

    【讨论】:

    • 我已经将 v-bind:value 更改为 id 而不是名称,所以这不是问题。但是,您将 id 连接到 url 的第一个建议奏效了。谢谢!
    • 不客气,通常我更喜欢将值绑定到对象,在这种情况下绑定到路由项
    猜你喜欢
    • 2021-04-11
    • 2021-12-06
    • 2021-03-24
    • 2020-09-27
    • 2020-03-22
    • 2019-12-14
    • 2020-01-05
    • 2019-08-02
    • 2020-10-26
    相关资源
    最近更新 更多