Django后端跨域

231 阅读2分钟

事情是这样的

我在学习vue的时候用,脚手架搭建了一个vue项目,然后呢启动项目时输入

npm run serve

就会在电脑上起一个node的服务嘛。

然后呢我自己的Django服务呢,是部署在在阿里云的机器上的,然后vue项目调接口的时候就有个报错了,查了一下是后端禁止跨域引起的。然后就开始面向百度编程了

具体操作是这样的

首先在安装依赖包

打开我的阿里云,也就是服务器的环境

输入👇这个

pip install django-cors-headers

然后打开项目目录下的settings.py

找到INSTALLED_APPS注册组件(亲测不注册也能用2020.12.02)

INSTALLED_APPS = (
...
'corsheaders',
...
)

然后找到MIDDLEWARE设置跨域中间件

MIDDLEWARE = [ 
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

来到最下面增加跨域主机设置

CORS_ORIGIN_ALLOW_ALL = True这个是允许所有访问

CORS_ALLOW_CREDENTIALS = True这个是允许携带cookie

CORS_ORIGIN_WHITELIST = (
'127.0.0.1:8080',
'localhost:8080',
'www.xxxx.com:8080',
'api.xxxx.com:8000'
)#这个是设置白名单

还有没有别的方法

那么由于我的服务部署的时候使用了Django + Nginx + uwsgi ,在百度的时候还发现了修改Nginx配置解决跨域问题的。直觉告诉我这是可行的,利用Nginx转发,反向代理应该都是可以。我就放个配置的方法供老板们参考一下。

Nginx.conf添加

如果不知道配置文件路径: 在你的机器上敲nginx -t

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

你就会看到上面👆👆👆👆👆这个

打开,添加下面👇👇👇👇👇这个

add_header Access-Control-Allow-Origin http://www.xxxx.com;
add_header Access-Control-Allow-Headers Origin,X-Requested-With,Content-Type,Accept;
add_header Access-Control-Allow-Methods POST,GET;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Origin http://www.xxxx.com;
add_header Access-Control-Allow-Headers Origin,X-Requested-With,Content-Type,Accept;
add_header Access-Control-Allow-Methods POST,GET;
add_header Access-Control-Allow-Credentials true;

最后这段仅供参考,因为我在Django上解决了,就没有操作过。

如果有需要,下次一定试试