參考文章: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裏面的內容按名字取出:
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()
}
});