问题
I want to implement a front-end and back-end data interaction with axios and django view. Now I have succeed in posting data to django view with code below.
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")
})
But when I want to return json from view to 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)
the browser has no change! Firstly, I tried to figure out why it occurred independently. The potential clue maybe lie in 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'),
]
Because I found that the initial url http://127.0.0.1:8000/main/
in my browser after clicking on the button to post data to getCommodityInfo view became http://127.0.0.1:8000/main/?searchKey=switch&category=Electronics
. This url seems not to match any url patterns in urls.py. So I tried to append an additional urlpattern path('?searchkey=<str:searchKey>&categroy=<str:category>/',views.getCommodityInfo, name = 'getCommodityInfo')
. Unfortunately, it doesn't work.
After that, I am searching for a long time on net. But no use. Please tell me whether my idea to solve right. Or try to give some ideas how to achieve this.Thanks in advance.
Edit 1 My console logs were asked.
This is my console log after click the button to post data.
And when I click on the alert, the browser go to http://127.0.0.1:8000/main/?searchKey=switch&category=Electronics
and the chrome network loading shows like:
And there are no log output in console.
Edit 2 There are some doubts on whether axios send the request by POST or GET, and I try to indentify it in my django view
My python console output this, meaning getCommodityInfo did indentify the request as POST(You could review my code)
Edit 3 @dirkgroten pointed out likely I have sended both POST and GET. So I give the whole code related in my template
And here is my form. And whole js related.
<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:
Acutally, I have found the mistake. It's all about the <form>
... The solution is here
来源:https://stackoverflow.com/questions/55274380/axios-unable-to-get-json-from-django-view