【问题标题】:How to integrate Gatsby with NodeJs Express Backend如何将 Gatsby 与 NodeJs Express 后端集成
【发布时间】:2023-03-09 03:21:01
【问题描述】:

我有 Gatsby 作为我的前端和 NodeJs/Express 来获取 API 数据。我用以下内容编辑了 gatsby-config.js

module.exports = {
  /* Your site config here */

  proxy: {
    prefix: "/api",
    url: "http://localhost:4000",
  },
}

使这项工作。

它在我的开发环境中有效,但在我运行 gatsby 生产构建时无效。当我运行 gatsby 生产构建并转到实时生产网站时,没有获取 nodeJS API 数据。我错过了构建步骤。

我愿意

盖茨比构建

盖茨比发球

【问题讨论】:

    标签: node.js reactjs express gatsby


    【解决方案1】:

    来自documentation

    请记住,代理仅在开发中有效(与 gatsby 开发),并由您来确保像 /api/todos 这样的 URL 指出生产中的正确位置。

    在生产中,您需要将 HTML 请求直接发送到后端服务器,无需代理。使用 Axios 之类的库:

    这里有一个来自 axios 存储库的 POST 请求示例:

    // Send a POST request
    axios({
      method: 'post',
      url: '/user/12345',
      data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
      }
    });
    

    您的浏览器会遇到 CORS 块。您的后端需要设置正确的响应标头,以便您的浏览器接受响应。在您的 express 应用中设置 cors:

    const Express = require("express");
    const BodyParser = require("body-parser");
    const cors = require("cors");
    
    const app = Express();
    app.use(BodyParser.text({ type: "text/plain" }));
    
    /* CORS */
    // app.use(cors()); // Enable cors for all origins
    app.use(cors({
      /** Use this when web frontend / production **/
      // origin: 'https://example.com',
    
      /** Use this when local frontend / development **/
      origin: "http://localhost:8000",
    }));
    

    【讨论】:

    • 当我为生产构建时,我对 package.json 做了哪些更改?
    • 对于盖茨比:什么都没有。对于 Express:yarn add express body-parser cors
    • 所以当我想同时构建生产环境时,我只需运行 Gatsby build 和 npm start?当我这样做时,Gatsby 无法识别节点后端,但它在开发中可以识别
    • 我对您的设置了解不足,无法回答您的问题。您可能想为这个新问题创建另一个帖子。
    • @PotaOnasys 听起来你不需要在这里使用代理。代理设置适用于您从位于同一域中的资源中获取数据的情况,即 Gatsby 位于 mysite.com 而您的 api 位于 mysite.com/api/posts。相反,您应该将后端 url 设置为环境变量并确保它指向您在生产中部署的服务器的正确 url。如果你只是在本地做gatsby build,那么你不需要设置env,直接使用你的localhost url即可。
    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2018-12-06
    • 2016-09-03
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多