路飞学城项目之前后端交互,跨域问题

分离的前后台交互

后台处理跨域

'''
https://github.com/ottoyiu/django-cors-headers/

安装django-cors-headers模块

在settings.py中配置
# 注册app
INSTALLED_APPS = [
...
'corsheaders'
]
# 添加中间件
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware'
]


# 允许跨域源
CORS_ORIGIN_ALLOW_ALL = False #True表示允许所有id访问
# 配置指定跨域域名(白名单)
CORS_ORIGIN_WHITELIST = [
'http://example.com'
]

# 允许ajax请求携带cookie
CORS_ALLOW_CREDENTIALS = True


# 注:前台请求头携带参数,中间件拒绝Access-Control-Allow-Headers错误,中间件要设置 default_headers
from corsheaders import defaults
在 default_headers 中添加 '前端ajax请求头里面的字段名'
'''

前台处理ajax

"""
1.安装axios
cnpm install axios --save
2.src/main.js配置

//配置axios,
import Axios from 'axios'
Vue.prototype.$axios = Axios;

// 允许ajax发送请求时附带cookie
axios.defaults.withCredentials = true;


# axios发生ajax请求
$axios({
utl: 'http://api.example.com/test', // 请求接口
headers: {}, // 携带请求头
method: 'post', // 还可以为post
  data: {}, // get通过param: {} 提交数据
})
"""
posted @ 2019-07-19 19:49  团子I不哭  阅读(166)  评论(1编辑  收藏  举报