You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

部署在Heroku的MERN应用仅登录接口可用,其余API接口失效

MERN应用部署Heroku后仅登录接口可用的问题解决

问题现象

将MERN应用部署到Heroku后,仅登录接口能正常响应,其余API接口均无反馈。尝试将前端代理地址从本地http://127.0.0.1:1000替换为Heroku应用地址https://carer-visit.herokuapp.com/,问题仍未解决。

正常工作的登录接口代码

export function login(userdata) {
  return async (dispatch) => {
    try {
      
      const loggedInUser = await axios.post(`/api/v1/carers/login`, userdata);

      let { data } = loggedInUser;

      localStorage.setItem('Authtoken', data.token);
      dispatch(setCurrentUser(data.user));
    } catch (error) {
      console.log(error.response.data);
      localStorage.removeItem('Authtoken');
      dispatch(setCurrentUserFailure());
    }
  };
}

无法工作的接口示例

export function fetchCarers() {
  return async (dispatch) => {
    dispatch(getCarers());

    try {
      const carerData = await axios.get('/api/v1/carers');

      let {
        data: {
          data: { users },
        },
      } = carerData;

      dispatch(setCarer(users));
    } catch (error) {
      dispatch(getCarerFailure());
    }
  };
}

问题根源

排查后发现问题出在后端生产环境的静态资源配置代码中:

if (process.env.NODE_ENV === 'production') {
      app.use(express.static('client/build'));
    
      app.get('*', (req, res) => {
        let filePath = path.resolve(__dirname, 'client/build', 'index.html');
    
        res.sendFile(filePath);
      });
    }

这段代码里,app.get('*')会匹配所有GET请求,包括API接口的请求,导致原本应该转发到API的请求被返回了前端的index.html,因此除了POST类型的登录接口外,其他GET类型的API接口都无法正常响应。

解决方法

将通配符*改为根路径/,仅在访问根路径时返回index.html,这样API接口的请求会被正常转发:

if (process.env.NODE_ENV === 'production') {
          app.use(express.static('client/build'));
        
          app.get('/', (req, res) => {
            let filePath = path.resolve(__dirname, 'client/build', 'index.html');
        
            res.sendFile(filePath);
          });
        }

内容的提问来源于stack exchange,提问作者oladimeji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 16:30:58