[英]Django + Vue. Can't connect params
所以,問題是我無法將Django REST與Vue連接起來。 當我從客戶端調用API時,它說:
Not Found: /api/private/
[16/Sep/2018 13:18:59] "GET /api/private/?city=London HTTP/1.1" 404 2129
這是我的代碼:
Vue功能
callWeather () {
const url = `${API_URL}/api/private/`
return axios.get(url, {
headers: {
Authorization: `Bearer ${AuthService.getAuthToken()}`
},
params: {
'city': 'London'
}
}).then((response) => {
console.log(response.data)
this.message = response.data || ''
})
}
Django api url:
urlpatterns = [
url(r'^api/public/', views.public),
url(r'^api/private/(?P<city>\w+)/$', views.private)
]
Django私人功能:
@api_view(['GET'])
def private(request, city):
return HttpResponse("City is: {}.".format(city))
您的axios.get
和private
視圖之間存在不匹配。 在您的axios.get
您通過GET參數(查詢字符串)傳遞數據。 在URL模式中,您將city
參數寫為URL的一部分。
GET
參數) 例如,您可以將urlpatterns
更改為:
urlpatterns = [
url(r'^api/public/', views.public),
url(r'^api/private/$', views.private)
]
在視圖中,您可以通過以下方式獲取與city
相關的值:
@api_view(['GET'])
def private(request):
city = request.GET.get('city')
return HttpResponse("City is: {}.".format(city))
如果city
參數不在查詢字符串中,則此處city
將為None
,因此您可能需要檢查該參數。
我們也可以在URL中對參數進行編碼,在這種情況下,您需要進行一些格式化,使得url
如下所示:
callWeather () {
const url = '${API_URL}/api/private/London/'
return axios.get(url, {
headers: {
Authorization: 'Bearer ${AuthService.getAuthToken()}'
},
}).then((response) => {
console.log(response.data)
this.message = response.data || ''
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.