Django 与小程序POST通信
相关代码解释:
//小程序js文件中通信触发
to_examine:function(){
wx.request({
url: 'http://10.180.9.74:8000/get_msg/', //仅为示例,并非真实的接口地址
method:"POST",
data: {
x: 'this is x',
y: 'this is y'
},
header: {
"Content-type": "application/json" // 默认值
},
success(res) {
console.log(res.data)
},
fail(res){
console.log('fail')
}
})
},
#django视图
import json
from django.http import HttpResponse
def get_msg(request):
if (request.method == 'POST'):
print("the POST method")
concat = request.POST
postBody = request.body
print(concat)
print(type(postBody))
print(postBody)
json_result = json.loads(postBody)
print(json_result)
return HttpResponse("Hello world")
# django中urls.py路由
urlpatterns = [
path('admin/', admin.site.urls),
path('get_msg/', views.get_msg),
]
# django中setting.py注意
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware', //要注释掉csrf检查
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]