【问题标题】:What is the most appropriate way to structure relative paths using a MERN stack?使用 MERN 堆栈构建相对路径的最合适方法是什么?
【发布时间】:2020-03-08 11:55:57
【问题描述】:

我正在部署一个 MERN 应用程序,并正在寻找有关为我的 API 与 React 路由构建相对路径的最佳方法的指导。下面是我的路线的一个子集。我的相对路径复制了文件夹结构,我不确定如何解决这个问题。

用户路线

module.exports = app => {
  app.get("/api/users", UserController.index);
...
};

用户操作

export const fetchUsers = () => async dispatch => {
  const response = await axios.get("api/users");
  dispatch({ type: FETCH_USERS, payload: response.data });
};

当我从 /users React 路由调用 fetchUsers 操作时,会出现问题。当我希望将请求发送到 /api/users 时,相对路由会将请求定向到 /users/api/users

更新

我通过为我的 api 调用实例化一个带有 baseurl 的 axios 对象解决了这个问题。

Axios 实例、API

import axios from "axios";

let URL = "";

if (process.env.NODE_ENV === "production") {
  URL = "herokuapp/api";
} else {
  URL = "http://localhost:3000";
}
export default axios.create({
  baseURL: URL
});

更新用户操作

export const fetchUsers = () => async dispatch => {
  const response = await rumbanroll.get("api/users");
  dispatch({ type: FETCH_USERS, payload: response.data });
};

【问题讨论】:

    标签: node.js reactjs express axios


    【解决方案1】:

    如果您的 API 与您的客户端托管在同一个域上,那么您可以使用绝对 url 来访问 API,而不是使用您在 axios url 中编写的相对 url,例如

    export const fetchUsers = () => async dispatch => {
      const response = await axios.get("/api/users"); // notice the / before api
      dispatch({ type: FETCH_USERS, payload: response.data });
    };
    

    【讨论】:

      猜你喜欢
      • 2020-11-16
      • 2015-11-15
      • 1970-01-01
      • 2012-05-09
      • 2017-11-09
      • 2018-09-20
      • 2021-07-27
      • 2011-01-08
      • 1970-01-01
      相关资源
      最近更新 更多