如何解决Nginx/React/Django:CORS 问题
在 ubuntu 服务器上,我使用 nginx 作为反向代理来为侦听端口 3000 的 react 应用程序提供服务(前端构建并使用 npm 包“serve”提供服务)。前端app使用axios调用django后端监听8000端口。
但是,每当我尝试向后端发送请求(例如登录失败)时,我都会收到 CORS 阻止错误,我尝试了许多类似问题的解决方案,但没有一个对我有用。
作为记录,该项目在使用 django-cors-headers 的本地机器上运行良好,仅当我将其放在服务器上并包含 nginx 时才会出现问题。以下是相关配置:
Nginx 配置
...
server_name <server_ip>;
location / {
#try_files $uri $uri/ =404;
proxy_pass http://localhost:3000;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
Django CORS 设置
...
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000"
]
#CORS_ALLOW_ALL_ORIGINS = True
ALLOWED_HOSTS = ['*']
...
Axios 配置
export const axiosInstance = axios.create({
baseURL: "http://localhost:8000/",timeout: 5000,headers: {
Authorization: "JWT " + localStorage.getItem("access_token"),"Content-Type": "application/json",accept: "application/json",},});
axiosInstance.interceptors.response.use(
(response: any) => response,async (error: any) => {
console.log(error);
const originalRequest = error.config;
if (
error.response.status === 401 &&
error.response.statusText === "Unauthorized"
) {
const refresh = localStorage.getItem("refresh_token");
const new_response = await axiosInstance.post("/auth/token/refresh/",{
refresh,});
localStorage.setItem("access_token",new_response.data.access);
localStorage.setItem("refresh_token",new_response.data.refresh);
axiosInstance.defaults.headers["Authorization"] =
"JWT " + new_response.data.access;
originalRequest.headers["Authorization"] =
"JWT " + new_response.data.access;
return axiosInstance(originalRequest);
}
return Promise.reject(error);
}
);
解决方法
问题是我将 axios 配置中的基本 url 保留为 localhost,我忘记了浏览器下载 js 文件并实际尝试访问客户端的 localhost 而不是服务器的。我发现的一种解决方案是使用 nginx 公开后端并将其用作基本 url。以下是修改后的配置:
Nginx 配置
...
server_name <server_ip>;
location / {
#try_files $uri $uri/ =404;
proxy_pass http://localhost:3000;
}
location /api/ {
proxy_pass http://localhost:8000/;
}
...
Axios 配置
...
baseURL: "http://<server_ip>/api",...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。