首页 > 解决方案 > React + Express 路由问题

问题描述

我有一个使用create-react-app命令创建的反应应用程序。

例如,我的反应应用程序中有以下路由。

/Home
/About
/Profile/:id

每个路由都在create-react-app.

在我的节点应用程序中,我已经为此应用程序编写了所有 api,并且可以使用 at myServer/api/v1/。在其他路线上,我只是返回build/index.html这是我为反应应用程序构建的。

这是server.js代码片段

app.use(express.static(__dirname + '/build'));

/* route path : 'api/v1/' */
app.use(require('./server/v1/routes')); 

app.get('/*', function (req, res) {
    return res.sendFile(path.join(__dirname, '/build/index.html'));
});

这是我的server/v1/routes/index.js文件

 var express = require('express');
 var router = express.Router();

 router.use('/api/v1/', require('./../api'));

 module.exports = router;

这是我的api/index.js文件

var express = require('express');
var router = express.Router();
var path = require('path');

import generalRouter from './controllers/general/router';
import profileRouter from './controllers/prifile/router';

//Login, forget password, reset password
router.use('/', generalRouter); 
router.use('/profile', profileRouter);

module.exports = router;

每个路由器文件都包含get/post/put/delete我的应用程序的相关方法。

反应路由:

 <BrowserRouter>
          <Switch>
            <Route exact={true} path='/' component={Home}/>
            <Route path='/About' component={About}/>
            <Route path='/ContactUs' component={ContactUs}/>
            ....
            <Route path='/Profile/:id?' component={Profile}/>
            <Route path='/VerifyAccount/:verifyLink?' component={VerifyAccount}/>
          </Switch>
        </BrowserRouter>

我所有的路由都可以正常工作,除了上面示例中带有参数的路由Profile/:id并且不工作。/VerifyAccount/:verifyLink?对于在我的应用程序的反应路由中使用参数的所有其他路由( )也是如此。它在我的节点服务器中工作,create-react-app但不适用于我的节点服务器。即使我注释掉我的api路线。

标签: node.jsreactjsexpressreact-router-v4

解决方案


推荐阅读