部署后出现 404 错误 axios post
After deployment getting 404 error axios post
目前,我正在尝试从 node.js 获取 axios 数据。我可以在本地 url 上获得结果,但是在我构建并部署它之后, post 方法出现 404 错误。所以我尝试使用get方法来测试它。它得到反应 html 结果。
当我在本地做的时候完全没问题。但只有当我构建和部署时它才不起作用。
我认为这是因为代理问题所以我安装了 http-proxy-middleware
库和
我尝试在我的 React 文件夹上设置 setupProxy.js
。
这个例子来自
“https://create-react-app.dev/docs/proxying-api-requests-in-development/”
但是还是不行。
我想知道是什么导致了这个问题。
//node.js
app.get("/test", (req, res) => {
res.send({ hello: "Hello world" });
});
const __dirname = path.resolve();
app.use(express.static(path.join(__dirname, "dist")));
app.get("/*", (req, res) => {
res.sendFile(path.join(__dirname, "dist", "index.html"));
});
//react
const getTest = () => {
axios
.get(`${backend}/test`)
.then(res => {
console.log(res.data);
})
.catch(err => console.log(err));
};
proxy configuration 仅适用于您在开发 React 应用程序时使用的 webpack-dev-server...
Keep in mind that proxy
only has effect in development (with npm start
), and it is up to you to ensure that URLs like /api/todos point to the right thing in production.
我建议只使用更简单的版本,将其添加到您的 package.json
"proxy": "http://localhost:5000",
您还应该确保您的 Express 应用配置为在开发和生产模式下处理 API 请求。为此,我建议使用与 front-end...
的请求中使用的相同的路由
app.get("/api/test", (req, res) => {
res.send({ hello: "Hello world" });
});
// or even better
app.use("/api", myApiRouter);
现在您的 React 应用程序可以在开发和生产模式下向 /api/test
发出请求
axios.get("/api/test").then(({ data }) => console.log(data));
在开发模式下,代理配置会将请求转发到您的 Express 应用。
在生产模式下,您的 Express 应用程序将通过 express.static()
为构建的 React 应用程序提供服务,因此它们将位于同一域中。
目前,我正在尝试从 node.js 获取 axios 数据。我可以在本地 url 上获得结果,但是在我构建并部署它之后, post 方法出现 404 错误。所以我尝试使用get方法来测试它。它得到反应 html 结果。 当我在本地做的时候完全没问题。但只有当我构建和部署时它才不起作用。
我认为这是因为代理问题所以我安装了 http-proxy-middleware
库和
我尝试在我的 React 文件夹上设置 setupProxy.js
。
这个例子来自
“https://create-react-app.dev/docs/proxying-api-requests-in-development/”
但是还是不行。
我想知道是什么导致了这个问题。
//node.js
app.get("/test", (req, res) => {
res.send({ hello: "Hello world" });
});
const __dirname = path.resolve();
app.use(express.static(path.join(__dirname, "dist")));
app.get("/*", (req, res) => {
res.sendFile(path.join(__dirname, "dist", "index.html"));
});
//react
const getTest = () => {
axios
.get(`${backend}/test`)
.then(res => {
console.log(res.data);
})
.catch(err => console.log(err));
};
proxy configuration 仅适用于您在开发 React 应用程序时使用的 webpack-dev-server...
Keep in mind that
proxy
only has effect in development (withnpm start
), and it is up to you to ensure that URLs like /api/todos point to the right thing in production.
我建议只使用更简单的版本,将其添加到您的 package.json
"proxy": "http://localhost:5000",
您还应该确保您的 Express 应用配置为在开发和生产模式下处理 API 请求。为此,我建议使用与 front-end...
的请求中使用的相同的路由app.get("/api/test", (req, res) => {
res.send({ hello: "Hello world" });
});
// or even better
app.use("/api", myApiRouter);
现在您的 React 应用程序可以在开发和生产模式下向 /api/test
发出请求
axios.get("/api/test").then(({ data }) => console.log(data));
在开发模式下,代理配置会将请求转发到您的 Express 应用。
在生产模式下,您的 Express 应用程序将通过 express.static()
为构建的 React 应用程序提供服务,因此它们将位于同一域中。