1.VUE请求接口
1.2 前后端分离的跨域问题
修改配置信息
注册
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework', #drf框架
'corsheaders', #跨域
'myapp',
]
添加中间件
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware', #添加中间件
]
配置参数,允许所有源访问
CORS_ORIGIN_ALLOW_ALL = True
vue使用axios请求数据
在src文件夹下创建ulits文件夹,并创建request.js文件进行axios的封装
# 封装
import Axios from 'axios'
export function get(url,params){
return Axios.get(url,params)
}
export function post(url,params){
return Axios.post(url,params)
}
export function put(url,params){
return Axios.put(url,params)
}
export function del(url,params){
return Axios.delete(url,params)
}
在根目录下创建vue.config.js配置跨域
module.exports = {
devServer : {
proxy:'http://127.0.0.1:8000/'
}
}
2. vue数据处理
2.1 vue进行数据渲染
<template>
<div>
<h3>展示人物信息</h3>
<table border="1px" width='200px' cellspacing='0px' align='center'>
<tr>
<th>姓名</th>
<th>性别</th>
</tr>
<tr v-for="(item,i) in peoplelist" :key="i">
<th>{{item.name}}</th>
<th>{{item.sex}}</th>
</tr>
</table>
</div>
</template>
<script>
import{get} from '../../utils/request'
export default {
name:'Index',
data(){
return{
peoplelist:[]
}
},
mounted(){
get('people/').then(resp=>{
console.log(resp);
this.peoplelist = resp.data
}).catch(err=>{
console.log(err)
})
}
}
</script>
<style>
</style>