后端(Django)
- 控制台安装Django-cors-header库
pip install django-cors-headers -i https://pypi.tuna.tsinghua.edu.cn/simple
- 修改settings.py(Django项目中的setting)
"application01.apps.Application01Config",
"corsheaders",
"corsheaders.middleware.CorsMiddleware",#注意位置!!
CORS_ALLOWED_ORIGINS = [
'http://localhost:8080', # Vue前端应用的地址
'http://example.com', # 其他允许的域名
]
前端(vue)
- 修改main.js,引入axios,并设置请求根路径即后端接口
import Vue from 'vue'
import App from './App.vue'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import router from './router';
import store from './store'
// 引入axios
import axios from 'axios'
// 为axios设置请求的根路径
axios.defaults.baseURL = 'http://127.0.0.1:8000';
// 设置公共请求头
axios.defaults.headers.common['Authorization'] = 'Bearer token';
Vue.prototype.$http=axios
Vue.use(ElementUI)
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')
- 运行vue项目npm run serve,检查控制台,是否输出后端html页面内容