我使用 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/