【发布时间】:2021-04-20 03:36:40
【问题描述】:
今天我在部署到 Heroku 后遇到了一个愚蠢的问题。我有一个 React 前端。和快递后端。这是一个社交媒体应用程序。所以在这个应用程序中,我有一个用户个人资料页面。在此页面中,我使用后端路由来获取用户的数据。所以一切都很好。但是一旦我刷新页面,它就会开始显示来自后端的 JSON 对象
刷新前。
刷新后
我仅在部署后遇到此问题。我正在分享我为将其部署到 heroku 而编写的所有代码
服务器 - package.json
{
"name": "server",
"version": "1.0.0",
"description": "Back-end of the dev-media front-end",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"keywords": [
"devr",
"dev-media"
],
"author": "Ratul-oss",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.0.1",
"cookie-parser": "^1.4.5",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.11.15",
"validator": "^13.5.2"
}
}
服务器 - App.js
require("dotenv").config();
const express = require("express");
const routes = require("./routes/routes");
const cors = require("cors");
const app = express();
const port = process.env.PORT || 8000;
app.use(routes);
app.use(cors());
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
app.listen(port, () => console.log(`Listening to http://localhost:${port}`));
您还可以查看 routes.js,我的所有后端路由/代码都在其中编写
const cookieParser = require("cookie-parser");
const express = require("express");
const UserData = require("../models/user");
const routes = express.Router();
require("../dbConnection");
const auth = require("../middlewares/auth");
const cors = require("cors");
const Posts = require("../models/posts");
const bcrypt = require("bcrypt");
const Comments = require("../models/comment");
routes.use(express.json());
routes.use(express.urlencoded({ extended: false }));
routes.use(cookieParser());
routes.use(cors());
// * all the get routes starts from here
routes.get("/auth", auth, (req, res) => {
res.status(200).send(req.user);
});
// for getting the data of a single user by the id
routes.get("/user/:id", async (req, res) => {
try {
const id = req.params.id;
const user = await UserData.findOne({ _id: id });
res.status(201).send(user);
} catch (err) {
res.status(404).json({ err: "User not found" });
}
});
// for getting the data of all users
routes.get("/users", async (req, res) => {
try {
const users = await UserData.find();
res.status(200).send(users);
} catch (err) {
res.status(400).json({ err: "Something is wrong" });
}
});
// for logging out the user
routes.get("/logout", auth, async (req, res) => {
try {
req.user.tokens = req.user.tokens.filter(
(token) => token.token !== req.token
);
res.clearCookie("jwt");
await req.user.save();
res.status(200).send("Succefuly logged out");
} catch (err) {
console.log(err, "from the routes line 23");
}
});
// for getting all the followers
routes.get("/followers/:id", async (req, res) => {
try {
const id = req.params.id;
const user = await UserData.findOne({ _id: id });
res.send(user);
} catch (err) {
console.log(err);
}
});
// for recieving all the posts
routes.get("/posts", async (req, res) => {
try {
const posts = await Posts.find();
res.send(posts);
} catch (err) {
console.log(err);
}
});
// to verify the user posts
routes.get("/post/:id", async (req, res) => {
try {
const id = req.params.id;
const posts = await Posts.find({ userId: id });
res.send(posts);
} catch (err) {
console.log(err);
}
});
// for getting the single post according to the post id
routes.get("/posts/:id", async (req, res) => {
try {
const id = req.params.id;
const post = await Posts.findOne({ _id: id });
res.status(200).send(post);
} catch (err) {
res.status(404).json({ err: "Post Not Found" });
}
});
// for getting the specific comments of a post
routes.get("/comments/:id", async (req, res) => {
try {
const id = req.params.id;
const comments = await Comments.find({ postId: id });
res.send(comments);
} catch (err) {
console.log(err);
}
});
// * all the delete routes starts from here
// for deleting the use account
routes.delete("/deleteAccount/:id", async (req, res) => {
try {
const id = req.params.id;
await UserData.findByIdAndRemove(id).exec();
res.clearCookie("jwt");
res.send("Account Deleted");
} catch (err) {
console.log(err);
}
});
// for deleting the post
routes.delete("/deletepost", async (req, res) => {
try {
const id = req.body.id;
await Posts.findByIdAndRemove(id).exec();
res.send("Post deleted");
} catch (err) {
console.log(err);
}
});
// for deleting a comment
routes.delete("/deleteComment/:id", async (req, res) => {
try {
const id = req.params.id;
await Comments.findByIdAndRemove(id).exec();
res.status(200).send("Deleted");
} catch (err) {
console.log(err);
}
});
// * all the post routes starts from here
// for registering the user
routes.post("/register", async (req, res) => {
try {
const {
name,
email,
bio,
password,
conPass,
country,
gender,
profession,
} = req.body;
if (
(!name, !email, !password, !conPass, !country, !gender, !profession, !bio)
) {
res.status(422).json({ err: "Please fill all the fields properly" });
}
const user = new UserData({
name,
email,
bio,
password,
conPass,
country,
gender,
profession,
});
const emailExists = await UserData.findOne({ email: email });
if (emailExists) {
res.status(401).json({ err: "Email already exists" });
}
if (password !== conPass) {
res.status(403).json({ err: "Password doesn't matched" });
} else if (password === conPass && !emailExists) {
const token = await user.generateToken();
res.cookie("jwt", token);
await user.save();
}
res.status(200).json({ success: "Your account has been registered" });
} catch (err) {
res.status(400).send("Something went wrong");
}
});
// the login route
routes.post("/loginuser", async (req, res) => {
try {
const { email, password } = req.body;
const user = await UserData.findOne({ email: email });
const isMatched = await bcrypt.compare(password, user.password);
if (isMatched) {
const token = await user.generateToken();
res.cookie("jwt", token);
res.status(200).json({ success: "Loggin Successful" });
} else if (!isMatched) {
res.status(403).json({ err: "Your login details are invalid" });
}
} catch (err) {
res.status(400).json({ err: "Invalid Credentials" });
}
});
// for posting any post
routes.post("/postsomething", async (req, res) => {
try {
const name = req.body.name;
const text = req.body.text;
const userId = req.body.userId;
const time = req.body.time;
const date = req.body.date;
if (!text) {
res.status(400).json({ err: "Please type something!" });
}
const post = new Posts({
name: name,
date: date,
time: time,
body: text,
userId: userId,
like: 0,
});
await post.save();
res.status(200).json({ success: "Your Post has been created" });
} catch (err) {
res.status(500).send(err);
}
});
// for posting a comment
routes.post("/postComment", async (req, res) => {
try {
const postId = req.body.postId;
const user = req.body.user;
const commentText = req.body.comment;
const userName = req.body.userName;
const comment = new Comments({
userName,
commentText,
user,
postId,
time: new Date().toLocaleTimeString(),
date: new Date().toLocaleDateString(),
});
await comment.save();
res.status(200).send("Comment Posted");
} catch (err) {
console.log(err);
}
});
// * all the put request starts from here
// for updating the user
routes.put("/updateUser", async (req, res) => {
try {
const { name, email, bio, profession, userId } = req.body;
await UserData.findById(userId, (err, updatedUser) => {
if (name) {
updatedUser.name = name;
}
if (email) {
updatedUser.email = email;
}
if (bio) {
updatedUser.bio = bio;
}
if (profession) {
updatedUser.profession = profession;
}
updatedUser.save();
res.status(200).send("Informations has been updated");
});
} catch (err) {
res
.status(400)
.send(
"Please fill all the fields. If you don't want to update on of them, please type the previous one"
);
}
});
// for following any user
routes.put("/followUser", async (req, res) => {
try {
const followerUser = req.body.authenticateduser; // follower
const followingUser = req.body.user; // this guy will get the follow
await UserData.findById(followingUser._id, (err, user) => {
// when any user will click on the follow button in the front-end, his / her data will be
// stored in the followers field as an object
user.followers = user.followers.concat({ follower: followerUser });
user.save();
res.send("Followed");
});
} catch (err) {
console.log(err);
}
});
// to unfollow an user
routes.put("/unfollowUser", async (req, res) => {
try {
const followerUser = req.body.authenticateduser; // unfollower
const followingUser = req.body.user; // this guy will get the unfollow
await UserData.findById(followingUser._id, (err, user) => {
user.followers = user.followers.filter((follower) => {
return follower.follower._id !== followerUser._id;
});
user.save();
res.send("Unfollowed");
});
} catch (err) {
console.log(err);
}
});
// for liking a post
routes.put("/likePost", async (req, res) => {
try {
const postId = req.body.postId;
const liker = req.body.user;
await Posts.findById(postId, (err, post) => {
post.like = post.like + 1;
post.likers = post.likers.concat({ liker: liker });
post.save();
res.send("Liked");
});
} catch (err) {
console.log(err);
}
});
// for unliking a post
routes.put("/unlikePost", async (req, res) => {
try {
const postId = req.body.postId;
const liker = req.body.user;
await Posts.findById(postId, (err, post) => {
post.like = post.like - 1;
post.likers = post.likers.filter(
(likerUser) => likerUser.liker._id !== liker._id
);
post.save();
res.send("unliked");
});
} catch (err) {
console.log(err);
}
});
module.exports = routes;
您可以查看我部署的应用程序并找出问题https://devr-dev-media.herokuapp.com/。首先打开一个帐户,然后转到您的个人资料页面,然后尝试重新加载。您将面临问题。
如果您需要更多信息,请告诉我。请帮我解决部署问题。感谢您抽出宝贵时间:)祝您有美好的一天。
【问题讨论】:
标签: javascript node.js express heroku