Axios无法从Django视图获取JSON

时间:2019-03-21 05:42:09

标签: django django-views axios django-urls

我想用axios和django视图实现前端和后端数据交互。现在,我已成功使用以下代码将数据发布到django视图。

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

但是当我想将json从视图返回到axios时:

def getCommodityInfo(request):
    if request.method=="POST":
        # get POST parameters
        searchKey = request.POST.get('searchKey')
        category = request.POST.get('category')
        print("Enter the POST view!  ", searchKey, category)
        # unique ID for each record for DB
        uniqueId = str(uuid4())
        # spider setting
        settings = {
            'unique_id': uniqueId,
            'USER_AGENT': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
        }
        # taskId to indentify each task
        task = scrapyd.schedule('JDSpider', 'getCommodityInfo',
                                settings=settings, searchKey=searchKey, category=category)

        print("It seems everything is running well? ")
        return JsonResponse({'taskId': task, 'uniqueId': uniqueId, 'status': 'started'},safe=False)

浏览器没有变化!首先,我试图弄清为什么它是独立发生的。 潜在的线索可能在于urls.py。

urlpatterns = [
    # eg:127.0.0.1:8000/main/
    path('', views.index, name = 'index'),
    path('getCommodityInfo/',views.getCommodityInfo, name = 'getCommodityInfo'),
    path('getCommodityCommentDetail/',views.getCommodityCommentDetail, name="getCommodityCommentDetail"),
    path('commodityInfo/<str:category>/<str:searchKey>/',views.commodityInfoPage, name = 'commodityInfoPage'),
    path('commentsInfo/<str:commodityId>/',views.commodityCommentPage,name = 'commodityCommentPage'),
    # path('?searchkey=<str:searchKey>&categroy=<str:category>/',views.getCommodityInfo, name = 'getCommodityInfo'),
]

因为我发现在单击将数据发布到 getCommodityInfo 视图的按钮后,浏览器中的初始 url http://127.0.0.1:8000/main/变为http://127.0.0.1:8000/main/?searchKey=switch&category=Electronics。该网址似乎与 urls.py 中的任何网址格式都不匹配。因此,我尝试附加一个urlpattern path('?searchkey=<str:searchKey>&categroy=<str:category>/',views.getCommodityInfo, name = 'getCommodityInfo')。不幸的是,它不起作用。

之后,我在网上搜索了很长时间。但是没用。请告诉我我的解决方案是否正确。或者尝试给出一些实现方法的想法。谢谢。


编辑1 询问我的控制台日志。

这是单击按钮发布数据后的控制台日志。

This is my console log after click the button to post data

当我单击警报时,浏览器转到http://127.0.0.1:8000/main/?searchKey=switch&category=Electronics,Chrome网络加载如下所示:

enter image description here

并且控制台中没有日志输出。


编辑2 对于axios是通过POST还是GET发送请求存在一些疑问,我尝试在django视图中对其进行识别

我的python控制台输出了此信息,这意味着 getCommodityInfo 确实将请求标识为POST(您可以查看我的代码)

enter image description here


编辑3 @dirkgroten指出我可能同时发送了POST和GET。因此,我在模板中提供了相关的整个代码

这是我的表格。与整个js相关。

<form action="" id="searchForm">
<label for="searchKey">KeyWords</label>
<input v-model="searchKey" palceholder="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>

<button v-on:click="startSpider"  class="btn btn-default" >Submit</button>
<p>KeyWords : ${ searchKey }</p>
<p>Category : ${ selected }</p>

</form>

<script type="text/javascript">
    var searchApp = new Vue({
        delimiters:['${','}'],
        el: "#searchForm",
        data:{
          searchKey:'',
          selected:'',
          options: [
            {text: 'Baby', value:'Baby'},
            {text: 'Book', value:'Book'},
            {text: 'Electronics', value:'Electronics'},
            {text: 'Fashion', value:'Fashion'},
            {text: 'Food', value:'Food'},
            {text: 'Health&Beauty', value:'Health&Beauty'},
            {text: 'Home', value:'Home'},
            {text: 'Industrial&Scientific', value:'Industrial&Scientific'},
            {text: 'Motor', value:'Motor'},
            {text: 'Pet', value:'Pet'},
            {text: 'Sports', value:'Sports'},
            {text: 'Other', value:'Other'},
          ]
        },
        created:function(){
          this.selected = "";
        },
        methods:{
          startSpider:function(event){
            console.log(this.searchKey);
            console.log(this.selected);
            alert("spider is ready to run!");
            var param = new URLSearchParams();
            param.append('searchKey',this.searchKey);
            param.append('category',this.selected);

            axios.post("{% url 'main:getCommodityInfo'%}",
                        param,
                        {headers:{'X-CSRFToken': this.getCookie('csrftoken')}})
                .then(response=>{
                  this.searchKey = "!!!";
                  this.category = "Baby";
                  console.log(response.data)
                  alert("response has been caught");
                  console.log(response.data)
                })
                .catch(error=>{
                  console.log(error);
                  alert("connection has error")
                })
          },
          getCookie:function(name) {
              var value = '; ' + document.cookie
              var parts = value.split('; ' + name + '=')
              if (parts.length === 2) return parts.pop().split(';').shift()
            },
        }
    });
</script>

1 个答案:

答案 0 :(得分:0)

很抱歉,我发现了错误。全部与<form> ...有关的解决方案是here