【问题标题】:Making POST to DRF using Axios使用 Axios 对 DRF 进行 POST
【发布时间】:2019-08-29 12:12:06
【问题描述】:

我正在尝试使用vuejs 内部的axios 库发出一个简单的POST 请求,但由于某种原因,DRF 没有接收到参数。当通过Postman 发出相同的请求时,它会接收参数。

VueJS

postLogin(credentials){
    return axios({
      method: "POST",
      url: "company/login/",
      data: credentials,
    }).catch(err => {
      return TreatErrors.treatDefaultError(err);
    })
  }

DRF

@action(methods=['post'], detail=False)
    # Debug set here shows POST comes empty from vuejs
    def login(self, request, pk=None):
        if not request.POST.get('email'):
            raise ValidationError({
                'message': 'You must provide an email'
            })

使用Chrome DevTools我可以清楚地看到参数正在发送到DRF

我的尝试 我尝试从Postman 处理每个Headers 并将其粘贴到axios 但没有任何运气

postLogin(credentials){
    return axios({
      method: "POST",
      url: "company/login/",
      data: credentials,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }).catch(err => {
      return TreatErrors.treatDefaultError(err);
    })
  }

【问题讨论】:

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


    【解决方案1】:

    基本上,我以错误的方式访问数据:

    从这里:

    if not request.POST.get('email'):
     raise ValidationError({
       'message': 'You must provide an email'
     })
    

    到这里

    data = request.data
    
    if not data.get('email'):
      raise ValidationError({
        'message': 'You must provide an email'
      })
    

    【讨论】:

    • 非常感谢您!上帝保佑! :)
    猜你喜欢
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    相关资源
    最近更新 更多