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