node.js - 如何将 Gatsby 与 NodeJs Express 后端集成

标签 node.js reactjs express gatsby

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

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

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

让这项工作成功。

它在我的开发环境中有效,但在我运行 gatsby 生产版本时无效。当我运行 gatsby 生产版本并访问实时生产网站时,未获取 nodeJS API 数据。我缺少一个构建步骤。

我愿意

Gatsby 构建

Gatsby 服务

最佳答案

来自documentation :

Keep in mind that proxy only has effect in development (with gatsby develop), and it is up to you to ensure that URLs like /api/todos point to the right place in production.

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

这是来自 axios 存储库的 POST 请求的示例:

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

您的浏览器将遇到 CORS 阻止。您的后端需要设置正确的响应 header ,以便您的浏览器接受响应。在您的 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",
}));

关于node.js - 如何将 Gatsby 与 NodeJs Express 后端集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58681837/

相关文章:

javascript - Sequelize 带有日期的 Where 语句

node.js - Mongoose 流 JSON 数据

javascript - 生成缩略图并上传到 Node 中的 s3 存储桶的最佳方法是什么?

javascript - 如何在现有的 Materialise css 按钮和导航栏中添加自定义 css 样式?

javascript - react : Failed to import a JavaScript class from a folder

node.js - ExpressJS 的请求主体类型

node.js - Yeoman 和 ExpressJS

javascript - 为什么这些符号链接(symbolic link)会发生无限递归循环

node.js - 类型为 '(req: Request, res: IResponse, next: NextFunction) => void' 的参数不可分配给类型为 'PathParams' 的参数与 express.js

javascript - 如何将 Express 与 TypeScript 结合使用