vue前端請求后端
-
在項目文件夾下下載axios
npm install axios --save
-
在前端頁面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()
}
}
后端解決跨域問題
-
安裝跨域相關模塊
pip install Django-cors-headers
-
在settings文件中添加配置
INSTALLED_APPS = [
......
'corsheaders',
]
MIDDLEWARE = [
// 要放在頂部
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
......
]
-
在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'
)
-