vue-element-admin 和 django的交互

 

vue前端请求后端

  1. 在项目文件夹下下载axios

    npm install axios --save

 

  1. 在前端页面vue的script中调用

    import Axios from 'axios';

    export default {

    // 在此中添加方法

    methods: {

    getData() {

    const api = 'http://127.0.0.1:8000/sys/sysuser/';

    var api1 = api + 'all';

    Axios.get(api1)

    .then (function (response) {

    console.log(response)

    })

    }

    },

    mounted() {

    this.getData()

    }

    }

 

后端解决跨域问题

  1. 安装跨域相关模块

    pip install Django-cors-headers

  2. 在settings文件中添加配置

    INSTALLED_APPS = [

    ......

    'corsheaders',

    ]

 

MIDDLEWARE = [

// 要放在顶部

'corsheaders.middleware.CorsMiddleware',

'django.middleware.common.CommonMiddleware',

......

]

 

  1. 在settings.py 中新增配置项

    CORS_ORIGIN_ALLOW_ALL = True

    CORS_ORIGIN_WHITELIST = (

    'google.com',

    'hostname.example.com'

    )

    CORS_ORIGIN_WHITELIST = ()

    CORS_ORIGIN_REGEX_WHITELIST = ()

    CORS_ALLOW_METHODS = (

    'GET',

    'POST',

    'PUT',

    'PATCH',

    'DELETE',

    'OPTIONS'

    )

    CORS_ALLOW_HEADERS = (

    'x-requested-with',

    'content-type',

    'accept',

    'origin',

    'authorization',

    'x-csrftoken'

    )

  2. 重启前后端,完成!!!!!

原文地址:https://www.cnblogs.com/yanruizhe/p/13608169.html