码迷,mamicode.com
首页 > 其他好文 > 详细

vue前后端分离

时间:2019-12-21 22:41:31      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:跨域问题   组件   交互   this   文件   跨域   django   install   问题   

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)
})

vue前后端分离

标签:跨域问题   组件   交互   this   文件   跨域   django   install   问题   

原文地址:https://www.cnblogs.com/agsol/p/12078267.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!