node.js - 使用 MERN 堆栈构建相对路径的最合适方法是什么?

标签 node.js reactjs express axios

我正在部署 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 });
};

最佳答案

如果您的 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 });
};

关于node.js - 使用 MERN 堆栈构建相对路径的最合适方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58824343/

相关文章:

node.js - 代码 HPE_INVALID_METHOD Node js Hapi js

Node.js + Mongoose [RangeError : Maximum call stack size exceeded]

javascript - 在 React.js 中隐藏组件的正确方法

javascript - Node.js 上使用 Express 的代理服务器多次包装回调

javascript - 如何操作 Twilio 数据对象? Node JS

node.js - 使用快速验证器 typescript 定义

node.js - 我的Node.js Web服务上的回调 hell 发送到elasticsearch

angularjs - 通过注入(inject)控制单元测试 Angular 误差

javascript - 如何在 typescript 中使用抽象类

javascript - react : Associate values of input fields with removed components