后台处理跨域
'''
https://github.com/ottoyiu/django-cors-headers/
安装django-cors-headers模块
在settings.py中配置
# 注册app
INSTALLED_APPS = [
# 自定义app
# 第三方app
'corsheaders'
]
# 添加中间件
MIDDLEWARE = [
# 放最上面
'corsheaders.middleware.CorsMiddleware',
]
# 允许跨域源,设为False,通过白名单允许部分跨域源
CORS_ORIGIN_ALLOW_ALL = False
# 配置指定跨域域名
CORS_ORIGIN_WHITELIST = [
'http://www.luffy.cn:8080'
]
# 允许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请求:axios
import axios from 'axios'
Vue.prototype.$axios = axios; // 把对象挂载vue中
//允许ajax发送请求时附带cookie
axios.defaults.withCredentials = true;
'''做完上面的步骤之后,在前端的任何地方都可以通过this.$axios()取它'''
# 3、在后台写一个接口测试一下:
路由: path('test/', views.TestAPIView.as_view())
视图:
from rest_framework.views import APIView
from rest_framework.response import Response
class TestAPIView(APIView):
def get(self, request, *args, **kwargs):
print(request)
return Response({
"status": 0,
"msg": "ok",
"result": {
"info": "test数据"
},
})
# 4、然后我们要在前端的代码中测试接口
前端页面加载的是Home.vue,里面导入了三个组件,我们选择Header.vue组件来测试,我们在这个组件的script的create中输入window.alert(123),create()意思是当该组件创建完成后要做的事,测试发现只要加载完毕就会弹窗123.所以我们前后台的跨域请求测试就写在这里。
# axios发生ajax请求
$axios({
utl: 'http://api.example.com/test', // 请求接口
headers: {}, // 携带请求头
method: 'post', // 还可以为post
data: {}, // get通过param: {} 提交数据
})
# 测试代码
created() {
this.this_nav = localStorage.this_nav;
//请求后台接口
this.$axios({
url: 'http://api.luffy.cn:8000/home/test/',
methods: 'get'
}).then(response => {
window.console.log(response.data)
})
},
由于前面已经对后台做了配置,这时访问就会正常打印内容。
上面的created()还可以简写,具体向后台发请求如下:
<template>
<div class="footer">
<ul>
<!-- 3、用for循环,渲染到页面,绑定一个key作为唯一标识 -->
<li v-for="nav in nav_list" :key="nav.name">
<router-link :to="nav.link">{{ nav.name }}</router-link>
</li>
</ul>
<p>Copyright © luffycity.com版权所有 | 京ICP备17072161号-1</p>
</div>
</template>
<script>
export default {
name: "Footer",
data(){
return {
//1、先在data里定义一个空的列表
nav_list: []
}
},
created(){
//2、向后台接口发请求,拿到返回的数据,赋值给定义的空列表
this.$axios.get('http://api.luffy.cn:8000/home/test/').then(response =>{
this.nav_list = response.data
})
}
</script>