【问题标题】:How to pass parameters in axios url?如何在axios url中传递参数?
【发布时间】:2020-03-31 12:32:08
【问题描述】:

我正在尝试在我的 Ruby Sinatra 项目中使用 Axios。 我的 ruby​​ 文件中定义了一个 url。

post '/follow/:id' do
# do something
end

在我的 erb 文件中,我试图将变量 in view 传递给我的内联脚本。

<body>
    <div id="follow_element">
        <button v-on:click="followUser">Follow</button>
    </div>

    <script>
        window.addEventListener('load', function(){
            const app = new Vue({
                el: "#follow_element",
                methods:{
                    followUser(){
                        axios.post("/follow", {
                            params: {
                                id: <%= @user.id %>
                            }
                        })
                    }
                }
            })
        })
    </script>
</body>

我想要的是,如果用户点击按钮,应用程序会点击 /follow/:id url 来更新结果。然而,我遇到了两个问题。 首先, 不起作用(@user 是此 erb 中可用的变量)。第二个是应用点击“/follow”端点,而不是“/follow/:id”端点。

你能给我一些建议吗?非常感谢。

【问题讨论】:

    标签: ruby axios


    【解决方案1】:

    请注意,当您编写此内容时:

    post '/follow/:id' do
    # do something
    end
    

    您现在将接受 POST 请求,例如:/follow/oneRandomIdfollow/124184965 等等...

    在这里,您正在向/follow 发出请求,传递不在 url 中的 POST 参数。这不起作用:

    axios.post("/follow", {
      params: {
        id: <%= @user.id %>
      }
    })
    

    为了修复它,您可以使用可用的@user.id 生成一个 URL 并发出 POST 请求,如下所示:

    axios.post("/follow/<%= @user.id %>")
    

    或者,如果您想向用户传递一些数据(POST 数据,而不是 URL 参数),您可以这样做:

    axios.post("/follow/<%= @user.id %>", {
      name: 'A beautiful name to insert to an user with that ID'
    })
    

    如果你仍然卡住,你也可以使用axios(config),我认为它在做什么更清楚,来自axios README page

    axios({
      method: 'post',
      url: "/follow/<%= @user.id %>",
      data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
      }
    });
    

    【讨论】:

    • 非常感谢。我为此挣扎了一整天。非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多