首页 > 解决方案 > axios.post 自动将 url 与我的参数拼接起来

问题描述

我想在前端实现一个带有 vue 和 axios 的 api:

methods:{
  startSpider:function(event){
    alert("spider is ready to run!");

    let data = {'searchKey':this.searchKey,
            'category':this.category,
            'num':this.num};
    axios.post("{% url 'main:getCommodityInfo'%}",
                data,
                {headers:{'X-CSRFToken': this.getCookie('csrftoken')}})
        .then(response=>{
          console.log(response.data)
        })
        .catch(error=>{
          console.log(error);
          alert("connection has error")
        })
  },

当我调用这个函数时,我希望从后端获取数据并停留在初始 url。它确实接收数据,但 url 很快改变了。

经过一番探索,我发现浏览器实现了两个请求!首先,POST,然后是 GET:

'searchKey':'switch', 'category':'electronic','num':60为例。 在此处输入图像描述

我的浏览器网址随后更改为 在此处输入图像描述

为什么会发生?我刚刚使用 POST 而不是 GET。axios 帖子似乎会自动将初始 url 与参数拼接起来。我尝试了很多方法,但都失败了。甚至我写了一个类似这样结构的小demo来测试,但是demo运行良好!发生了什么?请帮帮我...


更新我:给我的服务器行为(django-view)和我的路由器相关的是path('getCommodityInfo/',views.getCommodityInfo, name = 'getCommodityInfo')

def getCommodityInfo(request):
    print(request.body)
    return JsonResponse({"data":True}, safe=False)

更新二:给我的前端表格:

                <form>
                    <label for="searchKey">KeyWords</label>
                    <input v-model="searchKey" placeholder="Input Search Key" type="string" class="form-control" id="searchKey" name="searchKey">

                    <label for="category">Commodity Category</label>
                    <select v-model="selected" id="category" name="category">
                        <option v-for="option in options" v-bind:value="option.value">
                            ${option.text}
                        </option>
                    </select>
                    <br>
                    <label for="num">Amount</label>
                    <input v-model="num" placeholder="Input amount needed" type="string" class="form-control" id="num" name="num" >
                    <button v-on:click="startSpider"  class="btn btn-default">Submit</button>
                    <p>KeyWords : ${ searchKey }</p>
                    <p>Category : ${ selected }</p>
                    <p>Amount: ${ num }</p>
                </form>

标签: vue.jsaxios

解决方案


该错误是由于未设置按钮类型而发生的。我们可以检查一下

缺失值默认为提交按钮状态。

并且在前端表单中没有按钮类型,所以按钮类型将是提交按钮。当点击按钮时,它会自动发送一个获取请求。

修改按钮如下:

<button v-on:click="startSpider"  class="btn btn-default" type='button'>Submit</button>

推荐阅读