【问题标题】:App Engine service with apollo-express-server v2.x.x serving React app statically带有 apollo-express-server v2.x.x 的 App Engine 服务静态地为 React 应用程序提供服务
【发布时间】:2020-11-08 06:38:58
【问题描述】:

这不是一个问题,而是一个知识问题。我一直在深入研究 GAE 的文档、Youtube 视频和帖子,了解如何通过单个 App Engine 服务提供完整的 MERN stack 应用程序。

老实说,我对 App Engine 部署在幕后所做的工作没有深入的了解,但我知道它会从分配的默认路由(即 @ 987654321@).

基于这些知识,我认为完全有可能通过/graphql 端点静态地为构建的 React 应用程序提供服务并处理来自同一应用程序的传入查询。

例如:

  1. 这解决了 CORS,因为所有内容都具有相同的来源。
  2. 您将自己限制在一个 App Engine 服务上,这样您就可以继续使用免费层级服务:)

这是我的项目结构:

root/
 app/
  node_modules/
  build/ <----- React app built
  src/
  App.js
  index.js
  ...
 server/ <----- In here is the Apollo Express Server v2.x.x serving app/build generated above^
  index.js
 package.json
 node_modules/
 app.yaml <---- This file tells App Engine what to do and which routes to expose
 ...

我的 app.yaml

runtime: nodejs12

env_variables:
  PORT: 4000

handlers:
  - url: /
    static_files: app/build/index.html
    upload: app/build/index.html
  - url: /
    static_dir: app/build
  - url: /graphql
    script: auto <---- Supposedly App Engine is smart enough to understand what to do with this route.

我只是无法将我的 App Engine 服务从服务应用程序查询回 React 应用程序。

有谁知道我正在做的事情是否可行,或者没有办法使用 Apollo Server 配置 App Engine 以提供静态 web 应用程序 + 同时公开 /graphql 端点。

非常欢迎任何建议或想法!

--------------------- 更新 ------------- --------------------

根据GAEfan的建议,我更新了app.yaml文件:

是的,好吧!我认为这确实有效,我仍然在控制台上收到一些关于resources not found 的错误所以,这是build/ 的内部结构

build/
 static/
  css/
  js/
 asset-manifest.json
 favicon.ico
 index.html
 logo192.png
 manifest.json
 robots.txt
 service-worker.js

我已经以同样的方式将json|txt|map|ico资源添加到此建议中。

- url: /(.*\.(gif|png|jpg|css|js|json|txt|map|ico))$
  static_files: app/build/\1
  upload: app/build/.*\.(gif|png|jpg|css|js|json|txt|map|ico)$

这解决了找不到资源的问题。并且您的通配符已经解析了 /graphql 端点。由于某种原因,WebSocket 握手未正确建立,但我不确定这是否是 App Engine 的直接限制,或者该协议默认被阻止。

有人了解 App Engine 上的 Websockets 吗?

【问题讨论】:

    标签: node.js reactjs google-app-engine graph apollo-server


    【解决方案1】:

    还有更多问题,但我会将其添加为部分/临时答案...

    app.yaml 中的前 2 个 url 处理程序是重复的。 URL 处理与第一个匹配,并将所有内容发送到...index.html。我假设您在构建目录中有一些jscss 或其他静态文件。这些永远不会提供给浏览器。因此,您需要使用更好的正则表达式路由、通配符等。

    让我们一次做这些:

    handlers:
      - url: /$  # this '$' ends the match, so the url matches only the root domain
        static_files: app/build/index.html
        upload: app/build/index.html
    

    接下来,我们来测试.js.css等:

    - url: /(.*\.(gif|png|jpg|css|js))$
      static_files: app/build/\1
      upload: app/build/.*\.(gif|png|jpg|css|js)$
    

    然后(假设您有 graphql 正常工作,您可以在那里发送所有其他请求:

    - url: /graphql
      script: auto
    

    甚至:

    - url: /(.*) # catches everything else!
      script: auto
    

    在您的/build 目录中显示文件或目录树,我们可以确保我们已经考虑了所有内容。

    【讨论】:

    • 谢谢伙计!这绝对是正确提供静态文件的情况。现在我只有上面详述的 Websocket 问题。
    猜你喜欢
    • 1970-01-01
    • 2020-02-21
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多