【问题标题】:How to serve build folder in Koa?如何在 Koa 中提供构建文件夹?
【发布时间】:2019-02-12 15:30:43
【问题描述】:

我已经编写了简单的待办事项应用程序,并且正在尝试将其部署到 Heroku。 我之前部署在 heroku 上,我使用了 Express + React。在我的 server.js 文件中,有一段代码:

if (process.env.NODE_ENV === 'production') {
    app.use(express.static('client/build'));
    app.get('*', (req, res) => {
        res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
    });
}

如果应用程序处于生产状态,那段代码将服务于“build”文件夹,并且还会向每个请求发送“index.html”。

我需要类似的代码,但对于 Koa + React。 Koa 是一个非常简约的框架,所以我猜肯定是安装了额外的包,我不知道是哪些。 我尝试了 koa-sendkoa-static,但无法配置它们。 我该怎么做?

【问题讨论】:

    标签: reactjs heroku deployment koa


    【解决方案1】:

    我现在无法对此进行测试,但我认为它会是这样的:

    const Koa = require('koa');
    const Router = require('koa-router');
    const send = require('koa-send');
    const static = require('koa-static');
    
    const app = new Koa();
    const router = new Router();
    
    if (process.env.NODE_ENV === 'production') {
      app.use(static('./client/build'));
    
      router.get('*', async (ctx, next) => {
        try {
          await send(ctx, './client/build/index.html');
        } catch(err) {
          // TODO: handle err?
          return next();
        }
      });
    }
    
    app.listen(3000);
    

    【讨论】:

    • 我现在能够测试这段代码,它对我有用。如果您有任何其他问题,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 2015-02-21
    • 2019-09-02
    • 1970-01-01
    • 2023-03-21
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    相关资源
    最近更新 更多