如何将Strapi后端和ReactJS前端部署到单个Heroku应用程序

时间:2020-07-27 15:13:36

标签: node.js reactjs create-react-app strapi

是否有任何支持的方式如何将Strapi后端和ReactJS前端部署到单个Heroku应用程序中?

我已经成功部署了Strapi后端,但是完全无法理解或找到有关如何部署前端的教程。

2 个答案:

答案 0 :(得分:0)

在您的trapi应用程序中的以下目录中创建以下文件:

./ middlewares / serve-react / defaults.json

{
    "serve-react": {
        "enabled": true
    }
}

./ middlewares / serve-react / index.js

'use strict';

/**
 * Module dependencies
 */

// Node.js core.
const fs = require('fs');
const path = require('path');
const koaStatic = require('koa-static');

/**
 * Serve react hook
 */

module.exports = strapi => {

  return {
    /**
     * Initialize the hook
     */

    async initialize() {
      const {maxAge, path: publicPath} = strapi.config.middleware.settings.public;
      const staticDir = path.resolve(strapi.dir, publicPath || strapi.config.paths.static);

  strapi.router.get(
    '/*',
    async (ctx, next) => {
      const parse = path.parse(ctx.url);
      ctx.url = path.join(parse.dir, parse.base);

      await next();
    },
    koaStatic(staticDir, {
      maxage: maxAge,
      defer: false, // do not allow other middleware to serve content before this one
    })
  );

  // if no resource is matched by koa-static, just default to serve index file
  // useful for SPA routes
  strapi.router.get('*', ctx => {
    ctx.type = 'html';
    ctx.body = fs.createReadStream(path.join(staticDir + '/index.html'));
  });
},
  };
};

./ config / middleware.json

{
  "timeout": 100,
  "load": {
    "before": [
      "responseTime",
      "logger",
      "cors",
      "responses",
      "gzip"
    ],
    "order": [
      "Define the middlewares' load order by putting their name in this array is the right order"
    ],
    "after": [
      "parser",
      "router",
      "serve-react"
    ]
  }
}

答案 1 :(得分:0)

如果有人想知道穆罕默德·艾哈迈德(Muhammad Ahmad)的解决方案是否可行-是的,它可行。

最初,我专门使用MERN堆栈,并使用了两个文件夹-一个用于客户端,另一个用于服务器。根目录只有package.json。在Heroku上一切正常,所以我没想到很难将后端切换到Strapi ...

然后,我决定尝试将服务器端(Express)替换为Strapi。之后,存在将整个案例部署到Heroku并在单个Heroku应用程序上运行它的问题。

因此,项目结构为:

/root 
      - /client (React UI)
      - /server (Strapi)
      - package.json

为了使整个事情协同工作,有必要在内部进行一些修改

./ middlewares / serve-react / index.js:

 const staticDir = path.resolve(strapi.dir, clientBuildPath || strapi.config.paths.static);

其中clientBuildPath ../ client / build