Django配置跨域并開發測試接口
1.跨域原理
1. 首先瀏覽器安全策略限制js ajax跨域訪問服務器
2. 如果服務器返回的頭部信息中有當前域:
// 允許 http://localhost:8080 這個網站打開的頁面中的js訪問我Access-Control-Allow-Origin: http://localhost:8080// 允許攜帶cookie訪問我Access-Control-Allow-Credentials: true
那么, 瀏覽器可以讓js 請求該服務器
2.django cors設置:
1. 安裝包pip install django-cors-headers2. 注冊應用INSTALLED_APPS = [...# 添加 django-cors-headers 使其可以進行 cors 跨域’corsheaders’]3. 添加中間件MIDDLEWARE = [# 放在中間件第一個’corsheaders.middleware.CorsMiddleware’,...]4. 設置# CORS跨域請求白名單設置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 JsonResponseimport jsondef 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 測試接口
1http://192.168.56.100:8888/user/login/
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
