问题
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",
},
}
to make this work.
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.
I do
gatsby build
gatsby serve
回答1:
From the 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.
In production, you need to send your HTML requests directly to your backend server without a proxy. Use a library like Axios:
Here an example from the axios repo for a POST request:
// Send a POST request
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
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:
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",
}));
来源:https://stackoverflow.com/questions/58681837/how-to-integrate-gatsby-with-nodejs-express-backend