You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Gatsby与Postgres通过GraphQL连接?已写Node.js服务器却不知如何在Gatsby中使用

把Postgres数据通过GraphQL拉进Gatsby的可行方案

嘿,看你已经搭好了Node.js的GraphQL服务器,现在要把Postgres的数据导入Gatsby对吧?这里有几个实用的方案,适配你现有的架构:

方案一:用官方插件gatsby-source-graphql(最推荐)

这是Gatsby官方提供的插件,专门用来从远程GraphQL数据源拉取数据,完美匹配你已经有GraphQL服务器的场景。

步骤:

  1. 安装插件
npm install gatsby-source-graphql
# 或者用yarn
yarn add gatsby-source-graphql
  1. 在gatsby-config.js里配置数据源
    把你的Node.js GraphQL服务器地址填进去,同时给数据源起个标识名:
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-graphql`,
      options: {
        // 自定义类型名称,查询时会用到
        typeName: `PostgresAPI`,
        // 自定义字段名,作为查询的入口
        fieldName: `postgresData`,
        // 你的GraphQL服务器地址(替换成你实际的端口/域名)
        url: `http://localhost:4000/graphql`,
        // 如果服务器需要认证,这里可以加请求头,比如:
        // headers: {
        //   Authorization: `Bearer ${process.env.GRAPHQL_AUTH_TOKEN}`,
        // },
      },
    },
  ],
};
  1. 在Gatsby中查询数据
    启动Gatsby开发服务后,你可以在页面/组件里通过GraphQL查询拉取数据,比如:
query GetUsers {
  postgresData {
    users {
      id
      name
      email
    }
  }
}

你也可以通过Gatsby自带的GraphQL playground(http://localhost:8000/___graphql)测试查询,确认数据是否正常加载。

方案二:自定义数据源插件(适合复杂需求)

如果需要对数据做额外处理(比如转换格式、过滤数据),或者想更灵活地控制数据拉取逻辑,可以自己写一个简单的Gatsby数据源插件。

步骤:

  1. 在项目根目录创建一个自定义插件文件夹,比如gatsby-source-postgres-graphql
  2. 在文件夹里创建gatsby-node.js,编写数据拉取逻辑:
const { request } = require('graphql-request');

exports.sourceNodes = async ({ actions, createNodeId, createContentDigest }) => {
  const { createNode } = actions;

  // 调用你的GraphQL服务器获取数据
  const query = `
    query {
      users {
        id
        name
        email
      }
    }
  `;
  const response = await request('http://localhost:4000/graphql', query);

  // 将每条数据转换为Gatsby节点
  response.users.forEach(user => {
    const node = {
      ...user,
      id: createNodeId(`postgres-user-${user.id}`),
      internal: {
        type: `PostgresUser`,
        contentDigest: createContentDigest(user),
      },
    };
    createNode(node);
  });
};
  1. 在gatsby-config.js里引入这个自定义插件:
module.exports = {
  plugins: [
    // 引入自定义插件
    `./gatsby-source-postgres-graphql`,
  ],
};

之后你就可以用allPostgresUser这样的查询获取数据了。

关键注意事项

  • 确保服务器在构建时运行:Gatsby在开发或构建时需要访问你的GraphQL服务器,你可以用concurrently同时启动服务器和Gatsby:
    npm install concurrently --save-dev
    
    然后在package.json里加脚本:
    "scripts": {
      "develop": "concurrently \"node server.js\" \"gatsby develop\"",
      "build": "node server.js && gatsby build"
    }
    
  • 解决CORS问题:如果Gatsby开发服务访问服务器时出现CORS错误,记得在你的Node.js服务器里添加CORS中间件(比如Express的cors包):
    const cors = require('cors');
    app.use(cors());
    

内容的提问来源于stack exchange,提问作者tyskocz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:28:10