The API back-end has the following template: template The code for the back-end is the following: Note that I changed the user and password for my own credentials on mangodb cloud.
index.js
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';
import postRoutes from './routes/posts.js';
const app = express();
app.use(bodyParser.json({ limit: '30mb', extended: true }))
app.use(bodyParser.urlencoded({ limit: '30mb', extended: true }))
app.use(cors());
app.use('/posts', postRoutes);
const CONNECTION_URL = 'mongodb+srv://user:password@cluster0.fawpw.mongodb.net/authDB?retryWrites=true&w=majority';
const PORT = process.env.PORT|| 5000;
mongoose.connect(CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => app.listen(PORT, () => console.log(`Server Running on Port: http://localhost:${PORT}`)))
.catch((error) => console.log(`${error} did not connect`));
mongoose.set('useFindAndModify', false);
controllers/posts.js
import express from 'express';
import mongoose from 'mongoose';
import PostMessage from '../models/postMessage.js';
const router = express.Router();
export const getPosts = async (req, res) => {
try {
const postMessages = await PostMessage.find();
res.status(200).json(postMessages);
} catch (error) {
res.status(404).json({ message: error.message });
}
}
export const getPost = async (req, res) => {
const { id } = req.params;
try {
const post = await PostMessage.findById(id);
res.status(200).json(post);
} catch (error) {
res.status(404).json({ message: error.message });
}
}
export const createPost = async (req, res) => {
const { title, message, selectedFile, creator, tags } = req.body;
const newPostMessage = new PostMessage({ title, message, selectedFile, creator, tags })
try {
await newPostMessage.save();
res.status(201).json(newPostMessage );
} catch (error) {
res.status(409).json({ message: error.message });
}
}
export const updatePost = async (req, res) => {
const { id } = req.params;
const { title, message, creator, selectedFile, tags } = req.body;
if (!mongoose.Types.ObjectId.isValid(id)) return res.status(404).send(`No post with id: ${id}`);
const updatedPost = { creator, title, message, tags, selectedFile, _id: id };
await PostMessage.findByIdAndUpdate(id, updatedPost, { new: true });
res.json(updatedPost);
}
export const deletePost = async (req, res) => {
const { id } = req.params;
if (!mongoose.Types.ObjectId.isValid(id)) return res.status(404).send(`No post with id: ${id}`);
await PostMessage.findByIdAndRemove(id);
res.json({ message: "Post deleted successfully." });
}
export const likePost = async (req, res) => {
const { id } = req.params;
if (!mongoose.Types.ObjectId.isValid(id)) return res.status(404).send(`No post with id: ${id}`);
const post = await PostMessage.findById(id);
const updatedPost = await PostMessage.findByIdAndUpdate(id, { likeCount: post.likeCount + 1 }, { new: true });
res.json(updatedPost);
}
export default router;
models/postMessage.js
import mongoose from 'mongoose';
const postSchema = mongoose.Schema({
title: String,
message: String,
creator: String,
tags: [String],
selectedFile: String,
likeCount: {
type: Number,
default: 0,
},
createdAt: {
type: Date,
default: new Date(),
},
})
var PostMessage = mongoose.model('PostMessage', postSchema);
export default PostMessage;
routes/posts.js
import express from 'express';
import { getPosts, getPost, createPost, updatePost, likePost, deletePost } from '../controllers/posts.js';
const router = express.Router();
router.get('/', getPosts);
router.post('/', createPost);
router.get('/:id', getPost);
router.patch('/:id', updatePost);
router.delete('/:id', deletePost);
router.patch('/:id/likePost', likePost);
export default router;
**The problem is: when I run the command "npm start" on the server side the console displays "server running on port 5000" but when I open the link it displays the message " canno't get"(check the image attached). I checked if all the directories where correctly set up and I cant find the error! On the developer tools only output " error 404" ** Any idea?