Django + Vue。无法连接参数

Lal*_*buy 1 python api django django-rest-framework vue.js

所以,问题是我无法将 Django REST 与 Vue 连接起来。当我从客户端调用 API 时,它说:

Not Found: /api/private/
[16/Sep/2018 13:18:59] "GET /api/private/?city=London HTTP/1.1" 404 2129
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

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 || ''
      })
    }
Run Code Online (Sandbox Code Playgroud)

Django API 网址:

urlpatterns = [
    url(r'^api/public/', views.public),
    url(r'^api/private/(?P<city>\w+)/$', views.private)
]
Run Code Online (Sandbox Code Playgroud)

Django 私有函数:

@api_view(['GET'])
def private(request, city):
    return HttpResponse("City is: {}.".format(city))
Run Code Online (Sandbox Code Playgroud)

Wil*_*sem 5

您的axios.get, 和private视图之间存在不匹配。在您axios.get通过 GET 参数(查询字符串)传递数据。在 URL 模式中,您将city参数写为 URL 的一部分。

使用查询字符串GET参数)

例如,您可以更改urlpatterns为:

urlpatterns = [
    url(r'^api/public/', views.public),
    url(r'^api/private/$', views.private)
]
Run Code Online (Sandbox Code Playgroud)

在视图中,您可以获取与city通过关联的值:

@api_view(['GET'])
def private(request):
    city = request.GET.get('city')
    return HttpResponse("City is: {}.".format(city))
Run Code Online (Sandbox Code Playgroud)

如果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 || ''
      })
    }
Run Code Online (Sandbox Code Playgroud)