React and Nginx messing up urls when using axios, incorrect API calls

Viewed 1963

I'm running two applications on my device, one is django app hosted on apache localhost:8001 and second one is react app running on nginx localhost:8005. Also I'm using nginx as a proxy router, which is listening on port 80 and redirecting to backend if endpoint starts with /api and frontend if endpoint is /(anything). For example my domain is 'xyz.com'. Backend is running fine, but I'm getting big problem with React and axios. Axios calls api by domain like 'xyz.com/api/users/add/' and half of urls are working. But for few cases he is adding frontend url to axios request. For example 'xyz.com/edit-user/api/users/add/' and I have no idea why. Problem is 100% by the nginx or frontend. I have no clue why only for certain urls Axios is adding frontend url for API calls.

Here is nginx config:

server {
        listen 80;
        listen [::]:80;

        root /var/wwww/nginx;
        location  /api {
                proxy_set_header X-Forwarded_For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_post;
                proxy_redirect off;
                #rewrite ^/api(.*) $1 break;
                proxy_pass http://127.0.0.1:8001/;
        }
        location / {
                #rewrite ^/web(.*) $1 break;
                proxy_pass http://127.0.0.1:8005/;
        }
}

server {
        listen 8005;
        server_name localhost;

        location / {
                root /home/ubuntu/Frontend/idom/build;
                        index index.html index.htm;
        }
}

and here is auth.js:

import axios from 'axios';
import { createMessage, returnErrors } from './messages';

import { USER_LOADING, USER_LOADED, AUTH_ERROR, LOGIN_SUCCESS, LOGIN_FAIL, LOGOUT_SUCCESS, REGISTER_SUCCESS, REGISTER_FAIL } from './types';
import auth from '../reducers/auth';


// CHECK TOKEN & LOAD USER
// export const loadUser = () => (dispatch, getState) => {

//   // User Loading
//   dispatch({ type: USER_LOADING });

//   // Get token from state
//   const token = getState().auth.token;

//   // Headers
//   const config = {
//     headers: {
//       'Content-Type': 'application/json'
//     },
//   }

//   // If token, add to headers config
//   if (token) {
//     config.headers['Authorization'] = `Token ${token}`;
//   }

//   axios.get('http://127.0.0.1:8000/register/', config)
//     .then(res => {
//       console.log(res);
//       dispatch({
//         type: USER_LOADED,
//         payload: res.data
//       })
//     })
//     .catch(err => {
//       dispatch(returnErrors(err.response.data, err.response.status));
//       dispatch({
//         type: AUTH_ERROR
//       })
//     })
// }

// http://127.0.0.1:8000


// LOGIN USER
export const login = (username, password) => dispatch => {
  const config = {
    headers: {
      "Content-Type": "application/json"
    }
  }

  // Request Body
  const body = JSON.stringify({ username, password });

  axios.post('api/api-token-auth/', body, config)
  .then(res => {
    console.log(res);
    if (res.status === 200) {
      dispatch({
        type: LOGIN_SUCCESS,
        payload: res.data
      })
    }
  })
  .catch(err => {
    console.log(err.response.data)
    if (err.response.status === 400) {
      dispatch(createMessage({ loginError: 'Nieprawidłowy login lub hasło. Spróbuj ponownie' }));
      dispatch({
        type: LOGIN_FAIL
      })
    }
  })
}


// REGISTER USER
export const register = ({ username, email, telephone, password1, password2 }) => dispatch => {

  const config = {
    headers: {
      "Content-Type": "application/json"
    }
  }

  const body = JSON.stringify({ username, email, telephone, password1, password2 })

  axios.post('api/users/add', body, config)
  .then(res => {
    console.log(res.status)
    if (res.status === 201) {
      dispatch(createMessage({ registerSuccess: 'Rejestracja przebiegła pomyślnie. Możesz się zalogować' }))
      dispatch({
        type: REGISTER_SUCCESS,
        payload: res.data,
      })
    } 
  })
  .catch(err => {
    if (err.response.status === 400) {
      dispatch(createMessage({ userExists: 'Taki użytkownik już istnieje. Spróbuj ponownie' }));
      dispatch({
        type: REGISTER_FAIL
      })
    }
  })
}


// LOGOUT USER
export const logout = () => (dispatch, getState) => {

  // Get token from state
  const token = getState().auth.token;

  // Headers
  const config = {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Token ${token}`
    }
  }

  axios.post(`api/api-logout/${token}`, null, config)
  .then(res => {
    console.log(res);
    dispatch({
      type: LOGOUT_SUCCESS
    })
  })
  .catch(err => {
    console.log(err);
    dispatch(returnErrors('Błąd wylogowania', err.response.status));
  })
}

Problem is 100% by the nginx or frontend. I have no clue why only for certain urls Axios is adding frontend url for API calls.

1 Answers

First:

location / {
                #rewrite ^/web(.*) $1 break;
                proxy_pass http://127.0.0.1:8005/;
        }

Second:

location  /api {
                proxy_set_header X-Forwarded_For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_post;
                proxy_redirect off;
                #rewrite ^/api(.*) $1 break;
            

proxy_pass http://127.0.0.1:8001/; } And full config:

server {
        listen 80;
        listen [::]:80;

        root /var/wwww/nginx;
location / {
                #rewrite ^/web(.*) $1 break;
                proxy_pass http://127.0.0.1:8005/;
        }        
location  /api {
                proxy_set_header X-Forwarded_For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_post;
                proxy_redirect off;
                #rewrite ^/api(.*) $1 break;
                proxy_pass http://127.0.0.1:8001/;
        }
       
}

server {
        listen 8005;
        server_name localhost;

        location / {
                root /home/ubuntu/Frontend/idom/build;
                        index index.html index.htm;
        }
}
Related