I am working on a small project, learning MERN Stack.
I have an issue with the routes and i don't have a clue why it's not working.
My propertyRoutes file:
const {
getAllProperties,
getProperty,
createProperty,
saveProperty,
} = require("../controllers/propertyController");
const express = require("express");
const router = express.Router();
router.get("/", getAllProperties);
router.get("/:id", getProperty);
router.post("/create-property", createProperty);
router.post("/save-property", saveProperty);
module.exports = router;
My PropertyController file:
const { json } = require("body-parser");
const PropertyModel = require("../models/Property");
const getAllProperties = async (req, res) => {
console.log("all")
const properties = await PropertyModel.find().exec();
res.json({ properties: properties });
};
const getProperty = async (req, res) => {
const id = req.params.id;
const property = await PropertyModel.findById(id).exec();
res.json({ property: property });
};
const createProperty = async (req, res) => {
res.send({message: 'hello'})
// const property = new PropertyModel(propertyData);
// return property;
};
const saveProperty = async (req, res) => {
const body = req.body;
const foundProperty = await PropertyModel.findById(body.id).exec();
if (!foundProperty) {
return res.json({ error: "not found" });
}
foundProperty.name = body.name;
foundProperty.price = body.price;
try {
await foundProperty.save();
res.json(foundProperty);
} catch (err) {
console.error(err);
res.json({ error: err.message });
}
}
module.exports = { getAllProperties, getProperty, createProperty, saveProperty, newProperty };
My Index.js:
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const PropertyModel = require("./models/Property");
const bodyParser = require('body-parser');
const propertyRouter = require('./routes/propertiesRoutes');
const userRouter = require('./routes/userRoutes');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const mongoDBUrl =
"mongodb+srv://*************@book-vacation-cluster.vqjxuoh.mongodb.net/bookVacDB?retryWrites=true&w=majority";
mongoose.connect(mongoDBUrl, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "mongodb connection error;"));
app.use("/property", propertyRouter);
app.use("/property/:id", propertyRouter);
app.use("/property/save-property", propertyRouter);
app.use("/property/create-property", propertyRouter);
app.use("/user/create-user", userRouter);
app.use(function (req, res, next) {
res.status(404).send('Unable to find the requested resource!');
});
app.use(cors());
app.listen(3001, () => console.log("Server is running!"));
The issue is with the "/create-property" route, although it suppose to function exactly as the "/save-property" rout, it's not even hitting the end point. I have no idea what am i missing.... Appreciate any help.
