生产中的Create-React-App:找不到路线 [英] Create-React-App in production: Routes not found

查看:144
本文介绍了生产中的Create-React-App:找不到路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a fullstack app with Create-React-App and Express.js as the backend.

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

The development setup (CRA running on port 3000) is realized by CRA's proxies so I can forward certain routes directly to the backend (running on port 5000):

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

要注销用户,我有一条相应的路由:

For logging out a user I have a corresponding route:

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

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

And a logout button that points to this route:

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

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

In development mode, running :3000 and :5000, everything works perfectly. Clicking on on the button sets the URL in the browser which calls the route, the proxy forwards and the backend recognizes and handles the request properly => Session killed!

在生产模式下 (托管在Heroku上),根本找不到并没有触发该路线.服务器可能会由于以下配置而在网络"标签中提供静态html文件:

In production mode, hosted on Heroku, the route is simply not found and not triggered. In the network tab the server serves the static html file, maybe due to this configuration:

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,它会起作用:

If I logout the user programmatically, by calling the same route onClick, it works:

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

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

But why is the simple redirect of the browser with the <a> not working in production?

THX!

推荐答案

更改

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中的生产环境

这篇关于生产中的Create-React-App:找不到路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆