小程序vue 获取后台数据post 请求 报错:403:CSRF Failed: CSRF token missing or incorrect

时间:2024-03-26 17:34:22

参考文章:https://blog.csdn.net/lohiaufung/article/details/80792334

https://blog.csdn.net/lff1123/article/details/80254282

 

 

这是一个django的跨域访问问题。
django,会对合法的跨域访问做这样的检验,cookies里面存储的’csrftoken’,和post的header里面的字段”X-CSRFToken’作比较,只有两者匹配,才能通过跨域检验。否则会返回这个错误:CSRF Failed: CSRF token missing or incorrect

解决方法
由上面的分析可以得出,只要在POST请求的header添加一个字段’X-CSRFToken’,这个字段和cookie里面的‘csrftoken’一样就好了。

在post请求添加一个header,内容如下:

{headers: {'X-CSRFToken': this.getCookie('csrftoken')}
1
其中,getCookies是这样一个函数,用于将cookies里面的内容按名字取出:
小程序vue 获取后台数据post 请求 报错:403:CSRF Failed: CSRF token missing or incorrect

 小程序vue 获取后台数据post 请求 报错:403:CSRF Failed: CSRF token missing or incorrect

     getCookie (name) {
              var value = '; ' + wx.getStorageSync("csrftoken")
              var parts = value.split('; ' + name + '=')
              if (parts.length === 2) return parts.pop().split(';').shift()
            },
            send() { //发送反馈
                console.log(JSON.stringify(this.sendDate));
                console.log('cookie',wx.getStorageSync("csrftoken") + '; ' + wx.getStorageSync("sessionid"))
                if (this.sendDate.content.length === 0) {
                    uni.showModal({
                        content: '请描述您的疑惑',
                        showCancel: false
                    })
                    return
                }
                // wx.request({
                //       url : this.$serverUrl + '/api/feedback/update',
                //       method: "POST",
                //       data: {
                //         "feedback":JSON.stringify(this.sendDate.content)
                //       },
                //       header: {
                //         "Content-Type": "application/x-www-form-urlencoded",
                //         "cookie": wx.getStorageSync("csrftoken") + '; ' + wx.getStorageSync("sessionid")
                //       },
                //       success: function (res) {
                //         console.log("反馈",res.data);
                //         wx.navigateBack({
                //           delta: 1  //小程序关闭当前页面返回上一页面
                //         })
                //         wx.showToast({
                //           title: '反馈成功!',
                //           icon: 'success',
                //           duration: 2000
                //         })
                //       },
                //     })
                uni.request({
                    url: this.$serverUrl + '/api/feedback/update',
                    data: {
                       "feedback":this.sendDate.content
                    },
                    method: 'POST',  
                    header: {
                      'X-CSRFToken': this.getCookie('csrftoken'),
                      "Content-Type": "application/json",
                      'cookie': wx.getStorageSync("csrftoken") + '; ' + wx.getStorageSync("sessionid")
                    },
                    success: (res) => {
                        console.log('建议反馈',res)
                        if (typeof res.data === 'string') {
                            res.data = JSON.parse(res.data)
                        }
                        if (res.statusCode === 200 && res.data && res.data.ret === 0) {
                            uni.showModal({
                                content: '反馈成功',
                                showCancel: false
                            })
                            this.sendDate = {
                                content: ""
                            }
                        } else if (res.statusCode !== 200){
                            uni.showModal({
                                content: '反馈失败,错误码为:' + res.statusCode,
                                showCancel: false
                            })
                        } else {
                            uni.showModal({
                                content: '反馈失败',
                                showCancel: false
                            })
                        }
                    },
                    fail: (res) => {
                        console.log(JSON.stringify(res))
                    },
                    complete() {
                        uni.hideLoading()
                    }
                });