首页 > 解决方案 > Nginx/React/Django:CORS 问题

问题描述

在 ubuntu 服务器上,我使用 nginx 作为反向代理来服务于侦听端口 3000 的 react 应用程序(前端是构建的,并使用 npm 包“serve”提供服务)。前端应用使用 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);
  }
);

标签: reactjsdjangonginxaxiosnginx-reverse-proxy

解决方案


问题是我将 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",
...

推荐阅读