万物不为我所有,但为我所用|

注入灵魂

园龄:3年7个月粉丝:3关注:2

DJango + Vue 跨域问题解决

什么是跨域

同源: 协议 + 域名 + 端口号,三者完全相同
以上三个元素只要有一个不相同就是跨域

产生跨域异常的报错信息如下:
access to xmlhttprequest at 'http://ip:port1/api/xxx' from origin 'http://ip:port2' has been blocked by cors plicy: no 'accesss-control-allow-orgin' header is present on the requestred resource.
翻译:从源地址http:ip:port2 发起的到 http://ip:port1/api/xxx 的xmlhttprequest访问违反了同源策略:因为在请求头中没有access-control-allow-origin的值

跨域解决

一般使用前后端分离都需要使用跨域(比如:DJango + Vue)

前端配置

# vue.config.js
module.eports = {
devServer:{
hot: true,
port: devPort, // 当前环境的端口
open: true,
noInfo: false,
overlay: {
warnings: true,
errors: true,
},
},
proxy: {
'/xxx':{ // 此处xxx与Django中的app对应
target: 'https://0.0.0.0:8000', // 目标(后端)服务器地址
changeOrigin:true, // 是否修改源
pathrewrite: { // 重写url路径
'^/api': ''
}
}
}
}

后端配置

# settings.py
# pip install Django-cors-hearers
# 添加corsheaders应用
installed_app:[
...
'corsheaders',
...
]
# 添加corsheaders中间件
middleware_class = {
...
corheaders.middleware.corsmiddleware,
django.middleware.common.commonmiddleware,
...
}
# 跨域增加的配置
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATH',
'POST',
'PUT',
'VIEW'
)
CORS_ALLOW_HEADERS = (
'XMLHttpReqest',
'X_FILENAME',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-request-with',
'Pragma',
)

本文作者:注入灵魂

本文链接:https://www.cnblogs.com/totopian/p/16848071.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   注入灵魂  阅读(184)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 尚好的青春 孙燕姿
尚好的青春 - 孙燕姿
00:00 / 00:00
An audio error has occurred.