Nginx/React/Django: CORS issue

Viewed 1181

On a ubuntu server I am using nginx as a reverse proxy to serve a react app listening on port 3000 (the front is built and is served using the npm package "serve"). The front app uses axios to call a django backend listening on port 8000.

However, I keep getting a CORS blocked error whenever I try to send requests to the backend (e.g sign in fails), I tried many solutions from similar questions but none worked for me.

For the record, the project works fine on my local machine with django-cors-headers, the problem only occurs when I put it on the server and included nginx. Here are the relevant configs:

Nginx config

...
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 settings

...
# 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 config

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);
  }
);
1 Answers

The problem was that I left the base url in axios config as localhost, I forgot that the browser downloads the js files and actually tries to access the client's localhost not the server's. One solution I found is to expose the backend using nginx and use that as the base url. Here are the modified configs:

Nginx config

...
server_name <server_ip>;
location / {
            #try_files $uri $uri/ =404;
            proxy_pass http://localhost:3000;
}
location /api/ {
            proxy_pass http://localhost:8000/;
}
...

Axios config

...
baseURL: "http://<server_ip>/api",
...
Related