提问者:小点点

Express不加载页面,只返回json


当重新加载页面后,服务器只返回json而不是该页面时,就会出现问题

我正在使用React和return static files from build folder,还有express handles路由,当运行localhost时只在生产模式下复制一切正常

app.use('/auth', authRoutes);
app.use('/user', userRoutes);
app.use(['/dota2', '/csgo', '/lol'], generalRoutes);

if (process.env.REACT_APP_ENV === 'production') {
  console.log('Production is running');
  app.use('/', express.static(path.join(__dirname, '../build')));
  app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, '../build', 'index.html'));
  });
}

有路线

const router = Router();

router.get('/live', liveMatches);
router.get('/upcoming', upcomingMatches);
router.get('/past', pastMatches);
router.get('/:matchId', getMatchById);
router.get('/opponents/:tournamentId', opponents);
router.post('/past-team-matches', pastTeamMatches);

您可以访问mySite,您将看到json作为结果,但是如果您清除URL中的matchId并单击任何匹配,页面将正常加载

还有react-router

<ServiceRoute
            key={key}
            path={['/dota2', '/csgo', '/lol']}
            exact
            access
            component={Matches}
          />
          <ServiceRoute
            key={key}
            path={['/dota2/:matchId', '/csgo/:matchId', '/lol/:matchId']}
            exact
            access
            component={MatchInfo}
          />

共1个答案

匿名用户

让我们按照express在这种情况下所做的路线匹配:

  1. 查找/dota2/566624时,它将在此处匹配:app.use(['/dota2','/csgo','/lol'],generalRoutes);并返回JSON.
  2. 查找/dota2时,它与app.use(['/dota2','/csgo','/lol'],generalRoutes);不匹配,因此它将继续向下运行,直到与app.get('*',(req,res)=>{匹配,为React页面提供服务。

我在这里看到的问题是,您在React上为API和前端路由使用了完全相同的路由。 理想情况下,当从同一服务器为API和前端应用程序提供服务时,您应该为API路由加前缀,这样它们就不会与前端路由发生冲突。 假设您在API路由前添加:/API。 现在你我们有:

app.use('/api/auth', authRoutes);
app.use('/api/user', userRoutes);
app.use(['/api/dota2', '/api/csgo', '/api/lol'], generalRoutes);

// ... everything is the same down here
  1. /api/dota2/566624。 将与在第一次加载时返回JSON的端点匹配。
  2. /dota2/566624。 将不匹配JSON端点,并跟踪到加载React应用程序的'*'路由,以后,一旦加载了应用程序,该路由将由您在React应用程序上使用的路由器处理。

不要像我在上面的示例中所做的那样添加前缀,使用您一直用于此目的的常量router=router();。 我对前缀进行了硬编码,这样我可以使示例简短。

最后一个问题是:为什么在发展方面没有出现这种情况? 我没有所有的信息,但是我可以看到,您正在从不同于运行API的服务器上为前端应用程序提供服务; 在这种情况下,您不会有路由冲突,因为它们是来自不同端口的服务器,例如在localhost:8080上服务的前端和在localhost:5000上服务的API。

我希望这能帮上忙! 如果您需要信息,请评论!