如何将Gatsby与NodeJs Express后端集成 [英] How to integrate Gatsby with NodeJs Express Backend
问题描述
我将Gatsby作为前端,并使用NodeJs/Express来获取API数据.我用以下内容编辑了gatsby-config.js
I have Gatsby as my frontend and NodeJs/Express to fetch API data. I edited gatsby-config.js with the following
module.exports = {
/* Your site config here */
proxy: {
prefix: "/api",
url: "http://localhost:4000",
},
}
要使其正常工作.
它在我的开发环境中有效,但在我运行gatsby生产版本时不起作用.当我运行gatsby生产版本并转到实时生产网站时,未获取nodeJS API数据.我缺少构建步骤.
It works in my development environment, but not when I run the gatsby production build. When I run the gatsby production build and go to the live production website, the nodeJS API data is not being fetched. I'm I missing a build step.
我愿意
gatsby构建
盖茨比服务
推荐答案
来自
请记住,代理仅对开发有效(使用gatsby
开发),这取决于您确保/api/todos之类的网址
指向生产中的正确位置.
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 的库: In production, you need to send your HTML requests directly to your backend server without a proxy. Use a library like Axios: 这是axios回购中有关POST请求的示例: Here an example from the axios repo for a POST request: 您的浏览器将遇到CORS块.您的后端需要设置正确的响应头,以便您的浏览器将接受响应.在您的Express应用中设置cors: You will run into a CORS block by your browser. Your backend needs to set the right response header so your browser will accept the response. In your express app set the cors: 这篇关于如何将Gatsby与NodeJs Express后端集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
// Send a POST request
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
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",
}));