【问题标题】:Axios unable to get JSON from Django viewAxios 无法从 Django 视图中获取 JSON
【发布时间】:2019-08-11 22:49:06
【问题描述】:

想用axios和django view实现一个前后端数据交互。现在我已经成功地使用下面的代码将数据发布到 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&amp;category=Electronics。此 url 似乎与 urls.py 中的任何 url 模式都不匹配。所以我尝试附加一个额外的 urlpattern path('?searchkey=&lt;str:searchKey&gt;&amp;categroy=&lt;str:category&gt;/',views.getCommodityInfo, name = 'getCommodityInfo')。不幸的是,它不起作用。

在那之后,我在网上搜索了很长时间。但是没有用。请告诉我我的想法解决是否正确。或者尝试给出一些想法如何实现这一点。在此先感谢。


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

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

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

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


Edit 2 对于axios是通过POST还是GET方式发送请求存在一些疑问,我尝试在我的django视图中识别

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


编辑 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>

【问题讨论】:

  • 请粘贴您浏览器的控制台日志
  • @Nakul Narayanan 我已经编辑了我的问题。
  • 您发送的是 GET 请求而不是 POST
  • 实际上,django 视图确实将 axios 请求标识为 POST。那么GET请求是什么?从 django 视图'return JsonResponse'?
  • 从您发布的控制台日志图像中清楚地知道它是 GET 请求

标签: django django-views axios django-urls


【解决方案1】:

确实,我发现了错误。这都是关于&lt;form&gt;...解决方案是here

【讨论】:

    猜你喜欢
    • 2019-08-11
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 2023-01-09
    • 1970-01-01
    • 2021-04-12
    • 2016-01-24
    • 2021-11-20
    相关资源
    最近更新 更多