Django 跨域请求 解决 axios 未完待续
Posted yanxiatingyu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django 跨域请求 解决 axios 未完待续相关的知识,希望对你有一定的参考价值。
import django import os # os.environ.setdefault("DJANGO_SETTINGS_MODULE", "untitled5.settings") # project_name 项目名称 # django.setup() from django.utils.deprecation import MiddlewareMixin import importlib project_settings = os.environ[‘DJANGO_SETTINGS_MODULE‘] # print(project_settings)#untitled5.settings settings_ = importlib.import_module(project_settings) # <module ‘untitled5.settings‘ from ‘C:\Users\Administrator\Desktop\机器学习\untitled5\untitled5\settings.py‘> # print(settings_) CORS = getattr(settings_, ‘CORS‘) class MyMiddle(MiddlewareMixin): def process_response(self, request, response): if request.method == ‘OPTIONS‘: response[‘Access-Control-Allow-Headers‘] = CORS[‘Access-Control-Allow-Headers‘] response[‘Access-Control-Allow-Methods‘] = CORS[‘Access-Control-Allow-Methods‘] print("options") # if request.method == ‘POST‘: # response[‘Access-Control-Allow-Headers‘] = CORS[‘Access-Control-Allow-Headers‘] # response[‘Access-Control-Allow-Methods‘] = CORS[‘Access-Control-Allow-Methods‘] # print("post") response[‘Access-Control-Allow-Origin‘] = CORS[‘Access-Control-Allow-Origin‘] return response
CORS = { ‘Access-Control-Allow-Headers‘: ‘*‘, ‘Access-Control-Allow-Methods‘: ‘*‘, ‘Access-Control-Allow-Origin‘: ‘*‘ } MIDDLEWARE = [ ‘django.middleware.security.SecurityMiddleware‘, ‘django.contrib.sessions.middleware.SessionMiddleware‘, # ‘corsheaders.middleware.CorsMiddleware‘, ‘django.middleware.common.CommonMiddleware‘, # ‘django.middleware.csrf.CsrfViewMiddleware‘, ‘django.contrib.auth.middleware.AuthenticationMiddleware‘, ‘django.contrib.messages.middleware.MessageMiddleware‘, ‘django.middleware.clickjacking.XFrameOptionsMiddleware‘, ‘app01.myMiddle.MyMiddle‘ ]
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <div id="app"> {{ test }} <button v-on:click="asy_post">post</button> <button v-on:click="asy_get">get</button> </div> <script src="D://老男孩全套//Vue//vue.js"></script> <script src="D://老男孩全套//Vue//axios.min.js"></script> <script > new Vue({ el:‘#app‘, data(){ return { test:‘nihao你好‘, data:{"msg":"需要传递的数据"}, url:‘http://127.0.0.1:8000/index/‘, }; }, created(){ }, methods:{ asy_get(){ axios.get(this.url).then(function(response){ console.log(‘返回的数据‘); }).catch(function(error){ console.log(error); }); }, asy_post(){ axios.defaults.headers.common[‘k1‘]=‘k1‘; axios.post(this.url,this.data) .then(function(response){ console.log(response); }) .catch(function(error){ console.log(error); }); }, }, }) </script> </body> </html>
以上是关于Django 跨域请求 解决 axios 未完待续的主要内容,如果未能解决你的问题,请参考以下文章