前后端分离vue跨域

Django —— 中跨域配置 & axios
一. vue端

vue跨域配制(第一种方法)
在config文件夹下的index.js中配制
proxyTable: {
‘/api’: { //使用"/api"来代替"http://f.apiplus.c"
target: ‘http://127.0.0.1:8000/’, //源地址
changeOrigin: true, //改变源
pathRewrite: {
‘^/api’: ‘’ //路径重写
}
}
},

1
2
3
4
5
6
7
8
9
10
11
12
二. Django端

跨域(第二种方法)
用Django的第三方包 django-cors-headers 来解决跨域问题
操作步骤:
1.pip install django-cors-headers
2.在settings.py中添加’corsheaders.middleware.CorsMiddleware’,在SessionMiddleware和CommonMiddleware的中间
2.1.在INSTALLED_APPS里添加“corsheaders”
INSTALLED_APPS = [
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
‘corsheaders’,#新加
]
2.2.在MIDDLEWARE添加
‘corsheaders.middleware.CorsMiddleware’, ‘django.middleware.common.CommonMiddleware’
MIDDLEWARE = [
‘django.middleware.security.SecurityMiddleware’,
‘django.contrib.sessions.middleware.SessionMiddleware’,
‘corsheaders.middleware.CorsMiddleware’,#新加
‘django.middleware.common.CommonMiddleware’,#新加
‘django.middleware.common.CommonMiddleware’,
‘django.middleware.csrf.CsrfViewMiddleware’,
‘django.contrib.auth.middleware.AuthenticationMiddleware’,
‘django.contrib.messages.middleware.MessageMiddleware’,
‘django.middleware.clickjacking.XFrameOptionsMiddleware’,

]
2.3.在sitting.py底部添加
#跨域增加忽略
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = ()

对应的发送的请求的跨域

CORS_ALLOW_METHODS = (
‘DELETE’,
‘GET’,
‘OPTIONS’,
‘PATCH’,
‘POST’,
‘PUT’,
‘VIEW’,
)

CORS_ALLOW_HEADERS = (
‘accept’,
‘accept-encoding’,
‘authorization’,
‘content-type’,
‘dnt’,
‘origin’,
‘user-agent’,
‘x-csrftoken’,
‘x-requested-with’,
)

3.在settings.py中添加CORS_ORIGIN_ALLOW_ALL = True

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
三. axios用法

axios使用
axios完整写法:
this.axios({
method: ‘post’,
url: ‘/user/12345’,
data: {
firstName: ‘Fred’,
lastName: ‘Flintstone’
}
}).then((res)=>{
console.log(res)
}).catch((error)=>{
console.log(error)
});
post请求
this.axios.post(‘’,{}).then((res)=>{}).catch((error)=>{})
get请求
axios.get(‘/user?ID=12345’)
.then((response)=> {
console.log(response);
})
.catch((error)=> {
console.log(error);
});

在main.js里配置,该两行
import axios from ‘axios’
Vue.prototype.axios = axios //其它组件可以使用this.axios

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值