Nginx/React/Django:CORS 问题
Nginx/React/Django: CORS issue
在 ubuntu 服务器上,我使用 nginx 作为反向代理来为侦听端口 3000 的 React 应用程序提供服务(前端是使用 npm 包“serve”构建和提供的)。前端应用使用axios调用监听8000端口的django后端。
但是,每当我尝试向后端发送请求(例如登录失败)时,我总是收到 CORS 阻止错误,我尝试了类似问题的许多解决方案,但 none 对我有用。
郑重声明,该项目在我的本地机器上使用 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 保留为本地主机,我忘记了浏览器下载 js 文件并实际尝试访问客户端的本地主机而不是服务器的。我发现的一种解决方案是使用 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",
...
在 ubuntu 服务器上,我使用 nginx 作为反向代理来为侦听端口 3000 的 React 应用程序提供服务(前端是使用 npm 包“serve”构建和提供的)。前端应用使用axios调用监听8000端口的django后端。
但是,每当我尝试向后端发送请求(例如登录失败)时,我总是收到 CORS 阻止错误,我尝试了类似问题的许多解决方案,但 none 对我有用。
郑重声明,该项目在我的本地机器上使用 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 保留为本地主机,我忘记了浏览器下载 js 文件并实际尝试访问客户端的本地主机而不是服务器的。我发现的一种解决方案是使用 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",
...