部署在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
相关产品推荐
相关产品推荐

