如何在一个托管平台上部署Strapi和React?

4
大家好,我刚部署了一个 Strapi 和 React 项目,但是我将它们分别进行了托管,这看起来有些奇怪。请问如何将它们部署在同一台主机上?我在网上找不到任何关于这方面的指导。
像这样:
Strapi: https://nuclear-leagcy.herokuapp.com/admin https://nuclear-leagcy.herokuapp.com/graphql React: https://nuclear-leagcy.herokuapp.com 我认为我需要使用 Express 在 server.js 文件中定义应用程序,但当前还没有任何思路。
补充说明: 我想在 production 环境中使用 GraphQL,但不想在生产环境中显示 playground 接口,以免被他人盗用。
请问我该如何实现呢?
1个回答

2

如果使用3.0.0.beta.19.5在同一台服务器上部署Strapi + React,则需要执行以下操作。

rootDir = 意味着Strapi项目的根文件夹。

您需要创建一个新的中间件,即rootDir/middlewares/serve-react,并在其中放置这两个文件。

  1. defaults.json
{
  "serve-react": {
    "enabled": true
  }
}
  1. 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。注意,在此情况下,“after”属性末尾的“serve-react”是唯一添加的内容。
{
  "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"
    ]
  }
}

在 /public 目录下 - Christian
我正在使用Strapi-Beta,那段代码能在beta版本上运行吗? - Jacob Liu
嗨,@Christin,非常感谢您的回复,但您能详细解释一下吗?那段代码在我的电脑上运行不太好。我知道您是对的,但我想要更多的细节。您能再帮我一次吗? - Jacob Liu
正在3.0.0.beta.19.5版本中工作,我有一个正在运行的网站,我认为这超出了所提出的问题范围。如果需要更多澄清或关于特定问题的另一个问题,请记住Strapi有一个Slack用于帮助。 - Christian
1
谢谢,太棒了,它很好用,非常感谢您。再次感谢。 - Jacob Liu
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接