vue2中的跨域配置
main.js 中
// 发送请求 axios
import axios from 'axios'
//跨域的地址
axios.defaults.baseURL = 'http://127.0.0.1:8000'
//允许携带tooken
axios.defaults.withCredentials = true
//允许异步请求
axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
//携带token
axios.defaults.headers['token'] = localStorage.getItem('token')
//请求头
axios.defaults.headers.post['Content-Type'] = 'application/json'
Vue.prototype.$axios = axios
Vue.config.productionTip = false
django中的配置:
settings.py中:
# 配置跨域的白名单 CORS_ORIGIN_WHITELIST = ( 'http://localhost:8080', 'http://localhost:8000', 'http://localhost:8081', ) # 允许跨域携带Cookie CORS_ALLOW_CREDENTIALS = True # 设置允许请求的方法 CORS_ALLOW_METHODS = ( 'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS' ) # 设置请求的头部 CORS_ALLOW_HEADERS = ( 'x-requested-with', 'content-type', 'token', 'authentication', 'origin' )MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', //注释代码 'corsheaders.middleware.CorsMiddleware', //设置跨域中间件 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
django自动生成路由时,需要在主路由中设置
from rest_framework.routers import DefaultRouter from .views import * router = DefaultRouter() 生成路由对象 router.register('workers',DeparmentAPIView) DeparmentAPIView是视图集 urlpatterns = [ ] urlpatterns += router.urls 与原路由拼接