vue前后端分离

axios前后端交互

安装

一定要安装到`项目目录下

cnpm install axios
配置

在main.js中配置

//配置axios
import  axios from 'axios'
Vue.prototype.$axios = axios;
在组件中发送ajax请求
created(){
    //发送axios请求
    this.$axios({
        url:this.$settings.base_url+'/cars/',
        method:'get',
        params:{
        }
        }).then(response => { //请求成功成功之后执行
        this.cars = response.data;
        }).catch(error => {  //当网络状态码为4xx,5xx时执行
        console.log(error.response)
    });
},

错误信息都在error.response中

params:{}url拼接参数:任何请求都可以携带

data:{}数据包参数 get请求无法携带data参数

CORS跨域问题(同源策略)

django默认只对同源做响应(同源策略),存在跨域问题.

同源

http协议相同,ip服务器地址相同,app应用端口相同,三个都相同才叫同源.

跨域

http,ip,post三个有一个不同,就是跨域.

解决跨域问题

1)Django按照cors模块:
    >: pip install django-cors-headers
    
2)在settings注册模块,配置中间件:
    INSTALLED_APPS = [
        ...
        'corsheaders'
    ]
    MIDDLEWARE = [
        ...
        'corsheaders.middleware.CorsMiddleware'
    ]

3)在settings开启允许跨越:
    CORS_ORIGIN_ALLOW_ALL = True

js全局配置

assets的js文件下设置settings全局js文件

export default{
    base_url:'http://127.0.0.1:8000'
}

mian.js中配置全局js

//配置全局js
import settings from '@/assets/js/settings'
Vue.prototype.$settings = settings;

然后就可以在全局使用

this.$axios({
    url:this.$settings.base_url + `/car/${pk}/`
    }).then(response =>{
    this.car = response.data
    }).catch(error =>{
    console.log(error.response)
})

猜你喜欢

转载自www.cnblogs.com/agsol/p/12078267.html