vue.js - 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>
解决方案
该错误是由于未设置按钮类型而发生的。我们可以检查一下:
缺失值默认为提交按钮状态。
并且在前端表单中没有按钮类型,所以按钮类型将是提交按钮。当点击按钮时,它会自动发送一个获取请求。
修改按钮如下:
<button v-on:click="startSpider" class="btn btn-default" type='button'>Submit</button>
推荐阅读
- exception - setState() 或 markNeedsBuild() 在小部件树被锁定时调用 >。改变状态时
- spring-boot - th:text 中的 thymleaf 连接正在覆盖先前的值
- azure - 负载均衡器后面的 .NET Core VMS 上的 SSL
- python - 如何创建多个 MagicMock 实例
- c++ - 将向量的迭代器发送到函数中。(C++)
- crystal-reports-2010 - 如何在水晶报表中计算?
- node.js - 如何在 nodejs 中读取远程文件?
- flutter - 如何将按钮放置在屏幕底部中心?
- angular - Angular中的多个嵌套模块和路由
- java - Java-如何从示例中制作模板方法?