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',
)
posted @ 2022-11-01 16:04  注入灵魂  阅读(203)  评论(0)    收藏  举报