首页 文章

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

提问于
浏览
1

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

开发设置(在端口 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 回答

  • 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 中配置生产环境

相关问题