1.跨域原理
那么, 浏览器可以让js 请求该服务器
2.django cors设置:
‘corsheaders‘
]
3. 添加中间件
MIDDLEWARE = [
‘corsheaders.middleware.CorsMiddleware‘,
...
]
4. 设置
CORS_ORIGIN_WHITELIST = (
‘http://127.0.0.1:8080‘,
‘http://localhost:8080‘,
)
CORS_ALLOW_CREDENTIALS = True # 允许携带cookie
3.登录接口测试
3.1 user/usrs.py 中配置路由
urlpatterns = [
path(‘login/‘, views.login),
]
3.2 user/views.py 中写一个login视图函数
from django.http import JsonResponse
import json
def login(request):
body_dict = json.loads( request.body )
print(body_dict,8888888)
name = body_dict.get(‘name‘)
pwd = body_dict.get(‘pwd‘)
if not all([name, pwd]):
resp = {
"code": 1001,
"msg": ‘信息不全‘
}
return JsonResponse(resp)
if name == ‘zhangsan‘ and pwd == ‘123456‘:
resp = {
"code": 0,
"msg": ‘登录成功‘,
"data": {
"id": 1,
"name": ‘张三‘,
"age": 18
}
}
return JsonResponse(resp)
return JsonResponse({
"code": 1002,
"msg": ‘验证失败‘
})
3.3 测试接口
1
http://192.168.56.100:8888/user/login/
原文:https://www.cnblogs.com/yan2001/p/13771030.html