king-home

分离的前后台交互

 

后台处理跨域

\'\'\'
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
# 配置指定跨域域名
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配置
// 允许ajax发送请求时附带cookie
axios.defaults.withCredentials = true;
Vue.prototype.$axios = axios; // 把对象挂载vue中


# axios发生ajax请求
$axios({
utl: \'http://api.example.com/test\', // 请求接口
headers: {}, // 携带请求头
method: \'post\', // 还可以为post
  data: {}, // get通过param: {} 提交数据
})
"""

 

分类:

技术点:

相关文章: