【发布时间】:2020-09-15 22:05:00
【问题描述】:
我做了一些研究,发现了与此问题类似的帖子,但没有一个解决方案适合我。
我用 create-react-app 制作了一个 React 应用程序,然后我创建了一个 server.js 文件来拥有一个 Express Node 服务器。我已经学习了一些教程,看来我可以将我的 react 应用程序和我的 express 服务器放在同一个应用程序/构建中。
在本地,一切正常,我到达了我的 api 路线。但是当我在服务器上部署我的应用程序的构建时,我所有的 axios 请求响应都是我的应用程序中的 index.html 文件。我的代码中不允许我的 axios 请求到达我的 api 的问题是什么?
代码如下:
server.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")
);
带有 axios 的 Mail.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".
如果我把这个网址放在我的浏览器中,我有一个空白页面,就像我把一个不在我的前端反应路由器中的网址一样。
感谢您的帮助!
【问题讨论】:
标签: node.js reactjs express axios