一、跨域
在进行前后端开发的时候需要涉及到跨域的问题,跨域既可以在前端解决也可以在后端解决。前段解决的思路就是转换路径,将发出的请求的url地址转换成可以映射成的地址。后端的解决思路是将获取的地址转换成可以映射的地址。
1. 模型
1.1 前端跨域解决的模型
由于路由router的不同,因此在跨域请求的时候通过更换请求源为origin再对后端进行请求

1.2 后端跨域解决的模型
后端通过可接收的url来进行相同path的处理,揭示了前后端分析的关键点以及跨域解决的本质,即对相同的path进行不同的url的拼接,通过control的控制来调度相同的path。
后端通过可以接受的url,来对其进行路由映射

2. 方法
2.1 后端解决跨域
Django实例
2.1.1 通过以下指令安装corsheaders
# pip安装指令
pip install django-cors-headers
2.1.2 在配置文件中配置参数
1、进入项目的settings.py文件,进行如下配置
在INSTALLED_APPS中添加corsheaders
结果

2、在middleware中间添加corsheaders中的中间件
在middle中插入下面的中间件
'corsheaders.middleware.CorsMiddleware',
结果

3、在settings.py中添加以下的内容
# 设置post的跨域
CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True # 添加需要跨域的url
CORS_ORIGIN_WHITELIST = [ "https://example.com", "https://sub.example.com", "http://localhost:8080", "http://127.0.0.1:9000", "http://127.0.0.1:3000" ] # 允许使用的header
CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ]
结果

2.2 前端解决跨域
Vue实例
2.2.1 在配置文件中配置跨域路由
进入文件./config/index.js中,在ProxyTable中添加以下内容,如果存在多个跨域,就修改/api的名字和target中的内容。
'/api': { target: 'http://127.0.0.1:8000/',//设置你调用的接口域名和端口号 别忘了加http
changeOrigin: true, // secure: false, // 如果是https接口,需要配置这个参数
pathRewrite: { '^/api': '/'//这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add’即可
} }
结果
目录文件

配置的ProxyTable

2.2.2 调用
通过/api/后端的url地址来进行具体的响应,如我调用login/user.html,就可以书写成/api/login/user.html的url
结果

二、POST请求
在开发的过程中会涉及到请求方式的问题,而在Django中对于post请求是存在问题的,因此使用POST的请求方式的时候需要我们解决POST的冲突。解决post的请求有两个方法:
2.1 使用csrf_token来解决
在post请求的地方加上以下内容
# 添加下面的内容来解决post响应的问题
{% csrf_token %}
结果

2.2 注释掉中间件
注释掉settings.py的MIDDLEWARE中的django.middleware.csrf.CsrfViewMiddleware这个中间件

三、总结
以上是一些自己实践的总结,在网上也有很多方法,可以去尝试。 |