为什么response.data是一个html字符串而不是json对象?node.js,express.js,react



我的应用程序在本地主机上运行得很好,但一旦我部署到Heroku,我就遇到了这个错误:

当我在客户端控制台.log(response.data(时,我收到的是这个字符串,而不是带有我的用户信息的res.json:

"lt;!doctype html>lt;html lang=";en">lt;元字符集=";utf-8"/>lt;链接rel=";图标";href="攀升.png"/>lt;元名称=";视口";content=";宽度=装置宽度/>lt;元名称=";主题颜色";content="#000000"/>lt;元名称=";描述";content=";使用create-react应用程序创建的网站"/>lt;链接rel=";"苹果触摸图标";href="logo192.png"/>lt;链接rel=";"清单";href="manifest.json"/>攀登者国家<script defer=";推迟";src="/static/js/main.56943839.js">lt;链接href="static/css/main.a3875cba.css";rel=";样式表">您需要启用JavaScript才能运行此应用程序<div id=";根">quot;

app.use(
cors({
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
credentials: true,
origin: ["https://climber-nation.herokuapp.com/"],
methods: ["GET", "POST"],
})
);
//VALIDATE AUTHENTICATION TOKEN
const authenticateToken = (req, res, next) => {
try {
const token = req.headers["authorization"];
if (token == null) {
return res.sendStatus(401);
} else {
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (error, decoded) => {
if (error) {
return res.sendStatus(403);
} else {
req.user = decoded;
return next();
}
});
}
} catch (error) {
console.log(error);
return res.status(400).json({ error: error });
}
};
//AUTHENTICATION
app.get("/authentication", authenticateToken, async (req, res) => {
const username = req.user.username;
const allUserInfo = await db("users").select("*").where("username", username);
const image = await db("images")
.innerJoin("users", "images.image_id", "users.user_id")
.select("filename")
.where("username", username);
const imageFile =
"https://climber-nation.herokuapp.com/images/" + image[0]?.filename;
res.json({
allUserInfo: allUserInfo[0],
imageFile: imageFile,
});
});

一个朋友帮我解决了这个问题。

我的服务器中有这些代码行,但有一个小的拼写错误,还需要重新排列它们所在的位置。

服务器应用程序乞讨:app.use(express.static(path.join(__dirname, "build")));

服务器端应用程序:

app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "build", "index.html"));
});

我部署的应用程序现在已完全工作。

最新更新