Express / React - 在生产中,我的 axios 请求包含我的索引.html文件作为响应,并且没有到达我的快速服务器 api 路由



我做了一些研究,发现了这个问题的类似帖子,但没有一个解决方案对我有用。

我用create-react-app制作了一个React应用程序,然后我创建了一个服务器.js文件来拥有一个Express Node服务器。我已经遵循了一些教程,似乎我可以在同一个应用程序/构建中 pu 我的 react 应用程序和我的快速服务器。

在本地,一切正常,我到达我的 api 路由。但是当我在服务器上部署我的应用程序时,我所有的 axios 请求响应都是我的应用程序中的索引.html文件。我的代码中有什么问题不允许我的 axios 请求到达我的 api?

这是代码:

服务器.js

const connection = require("./conf");
const path = require("path");
const app = express();
app.use(express.json());
app.use(
express.urlencoded({
extended: true,
})
);
app.post("/api/user", (req, res) => {
const formData = req.body;
connection.query("INSERT INTO user SET ?", formData, (err, results) => {
if (err) {
res.status(500).send("Error");
} else {
res.sendStatus(200);
}
});
});
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, ".build/index.html"));
});
app.listen(8080, () =>
console.log("Express server is running on localhost:8080")
);

邮件.js 带公理

axios
.post(
"/api/user",
{
email: "xxx",
name: "xxx"
},
{ withCredentials: true }
)
.then((response) => {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

以及 Axios 的回应

{data: "<!doctype html><html lang="en"><head><meta charset…s/main.f398f833.chunk.js"></script></body></html>", status: 200, statusText: ""

在控制台中,我有一个很好的网址:

xhr.js:178 XHR finished loading: POST "https://www.mywebsite.com/api/user".

如果我把这个网址放在我的浏览器中,我有一个空白页,就像我把一个不在我的前端反应路由器中的网址一样。

感谢您的帮助!

你是在package.json中放置代理还是设置axios的基本URL

最新更新