生产中的 Create-React-App:未找到路由

IT技术 reactjs express heroku proxy create-react-app
2021-05-12 07:03:47

我有一个以 Create-React-App 和 Express.js 作为后端的全栈应用程序。

开发设置(在端口 3000 上运行的 CRA)由 CRA 的代理实现,因此我可以将某些路由直接转发到后端(在端口 5000 上运行):

"proxy": {
    "/auth/*": {
      "target": "http://localhost:5000"
    },
    "/api/*": {
      "target": "http://localhost:5000"
    }
}

为了注销用户,我有一个相应的路线:

app.get('/api/logout', (req, res) => {
    req.logout();
    res.redirect('/');
});

还有一个指向这条路线的注销按钮:

<a key="logout" href="/api/logout">Logout</a>

在开发模式下,运行 :3000 和 :5000,一切正常。单击按钮设置浏览器中调用路由的 URL,代理转发,后端正确识别和处理请求 => 会话被终止!

在生产模式下,托管在 Heroku 上,根本找不到路由也不会触发。在网络选项卡中,服务器提供静态 html 文件,可能是由于以下配置:

if (process.env.NODE_ENV === 'production') {

    app.use(express.static('client/build'));

    const path = require('path');
    app.get('*', (req, res) => {
        res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
    });
}

如果我以编程方式注销用户,通过调用相同的路由onClick,它可以工作:

await axios.get('/api/logout');

但是为什么浏览器的简单重定向<a>在生产中不起作用?

谢谢!

1个回答

改变

if (process.env.NODE_ENV === 'production') {

app.use(express.static('client/build'));

const path = require('path');
app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}

对此:

let root = path.join(__dirname, 'client', 'build');
app.use(express.static(root));
app.use(function(req, res, next) {
if (req.method === 'GET' && req.accepts('html') && !req.is('json') && 
  !req.path.includes('.')) {
     res.sendFile('index.html', { root });
  } else next();
});

也许这有帮助:在 create-react-app 中配置生产环境