django - React 和 Nginx 在使用 axios 时弄乱了 url,不正确的 API 调用

标签 django reactjs nginx url deployment

我在我的设备上运行两个应用程序,一个是托管在 apache localhost:8001 上的 django 应用程序,第二个是 react 应用程序在 nginx localhost:8005 上运行。我还使用 nginx 作为代理路由器,它正在监听端口 80 并在端点以/api 和前端开头时重定向到后端如果端点是/(anything)。例如,我的域是 'xyz.com'。后端运行良好,但我遇到了 React 和 axios 的大问题。 Axios 按域调用 api,如 'xyz.com/api/users/add/' 并且一半的 url 正在工作。但在少数情况下,他会向 axios 请求添加前端 url。例如 'xyz.com/edit-user/api/users/add/' 我不知道为什么。 问题是 100% 由 nginx 或前端造成的。我不知道为什么只有某些 url Axios 才为 API 调用添加前端 url。

这里是 nginx 配置:

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

这里是 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));
  })
}

问题 100% 出自 nginx 或前端。我不知道为什么只有某些 url Axios 才为 API 调用添加前端 url。

最佳答案

首先:

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

关于django - React 和 Nginx 在使用 axios 时弄乱了 url,不正确的 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62654250/

相关文章:

reactjs - 即使 screen.debug() 显示文本存在,React 测试库也无法找到文本

nginx 重写帖子数据

python - 使用 egg 模块时同步 django-piston 模型

Django动态表单ValidationErorr

javascript - React 应用程序检测用户是否刷新窗口或导航离开

reactjs - 导入 css 和 sass 文件 nextjs 7

python - 将一个应用程序用于多个 uwsgi 实例

node.js - 502 错误网关 Node JS/MongoDB AWS Elastic Beanstalk

python - 如何使 django 评论模型字段不需要站点

Django 应用程序重定向所有 URL