我的应用程序在本地主机上运行得非常好,但一旦我部署到Heroku,我就遇到了以下错误:
当我在客户端使用console.log(response.data)时,我收到了这个字符串,而不是带有我的用户信息的res.json:
"
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,
});
});
一个朋友帮我解决了。
我的服务器上有这几行代码,但是有一个小小的打字错误,还需要重新安排它们的位置。
服务器应用程序的请求:<代码>应用程序使用(express.static(path.join(__dirname,“build”))代码>
服务器应用结束:
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "build", "index.html"));
});
我部署的应用现在已完全正常工作。