【问题标题】:Axios POST request from Vuejs to Django rest framework从 Vuejs 到 Django REST 框架的 Axios POST 请求
【发布时间】:2023-03-16 02:38:01
【问题描述】:

我用 vuejs 和 django rest 框架创建了一个 rest api。问题是当我提出发布请求时。 通过获取请求,他可以工作,但不能通过发布请求。

axios
      .get('http://127.0.0.1:8000/api/users/')
      .then(response => (this.info = response.data))
axios
      .post('http://127.0.0.1:8000/api/users/', {
        params : {
          email : "test@gmail.com",
          username : 'test'
        }
      })
      .then(response => (this.info = response.data))
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

我的 get 请求有效,但我的 post 请求无效。在我的控制台中,我有:http://127.0.0.1:8000/api/users/?username=test&email=test@gmail.com 400(错误请求) 当我观看网络时,我有 {"username":["This field is required."]}

我不明白为什么会出现这个错误。

【问题讨论】:

    标签: django vue.js django-rest-framework axios


    【解决方案1】:

    axios 中的参数用于查询字符串

    试试

      axios
        .post('http://127.0.0.1:8000/api/users/', {
          email : "test@gmail.com",
          username : 'test'
        })
        .then(response => (this.info = response.data))
    

    发布时,您不想将信息作为查询字符串发送,而是作为数据发送。

    另一个签名是

    axios({
      method: 'post',
      url: 'http://127.0.0.1:8000/api/users/',
      data: {
        email : "test@gmail.com",
        username : 'test'
      }
    }).
    .then(response => (this.info = response.data))
    

    您可以在此处查看文档: https://github.com/axios/axios#example

    所以你得到“用户名是必需的”的原因是你的服务器正在读取数据/有效负载,而不是查询字符串。它没有找到任何发送的用户名并让您知道。

    【讨论】:

    • 没问题,如果这对您有用,那么我将不胜感激您将答案标记为正确答案。
    猜你喜欢
    • 2020-10-05
    • 2018-12-20
    • 2016-04-07
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多