前后台交互:axios

安装
1
2
3
>: cd 项目目录
>: cnpm install axios --save

配置:main.js
1
2
3
import Axios from 'axios'
Vue.prototype.$axios = Axios;

跨域问题(同源策略):Access-Control-Allow-Origin => CORS
1
2
3
4
5
前提:前台向后跳请求数据
1)服务器不一致 - ip
2)应用不一致 - 端口
3)协议不一致 - http <-> https

django解决跨域
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
'''
1)安装django-cors-headers模块

2)在settings.py中配置
# 注册app
INSTALLED_APPS = [
...
'corsheaders'
]
3)添加中间件
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware'
]
4)允许跨域源
CORS_ORIGIN_ALLOW_ALL = True
'''

axios请求方式

get

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
this.$axios({
url: 'http://localhost:8000/test/data/',
method: 'get',
params: {
usr: 'zero',
pwd: '000'
}
}).then((response) => {
console.log(response.data)
}).error((error) => {
console.log(error)
});


this.$axios.get('http://localhost:8000/test/data/', {
params: {
usr: 'zero',
pwd: '000'
}
}).then((response) => {
console.log(response.data)
}).error((error) => {
console.log(error)
});

post

1
2
3
4
5
6
7
8
9
10
11
12
13
this.$axios({
url: 'http://localhost:8000/test/data/',
method: 'post',
data: {
username: 'owen',
password: '123'
}
}).then((response) => {
console.log(response.data)
}).error((error) => {
console.log(error)
});