Hello i am building a REST api the problem is whenever i try to get information from the body i get a blank object. I've done this before and i know this is how its supposed to work so my guess is i made a silly mistake when configuring the server but so far i can't seem to find it. So i ask for your help!
Here's my server file:
import dotenv from "dotenv";
dotenv.config();
import express from "express";
import cors from "cors";
import router from "./routes/router.js";
import mongoose from "mongoose"
mongoose.connect(process.env.MONGO_URI);
const db = mongoose.connection;
const app = express();
const PORT = process.env.PORT || 8000;
app.use(express.json());
app.use(express.urlencoded({ extended:true }));
app.use("/", router);
app.use(cors({
origin: '*',
methods: "GET, POST, PUT, DELETE",
optionsSuccessStatus: 200
}));
app.get("/", (req, res) => {
res.json("Petko");
});
app.listen(PORT, console.log(`server runs at port: ${PORT}`));
Here's the route for the post request:
router.post("/articles/new", async(req, res) => {
const body = req.body;
console.log(body);
const newArticle = new Articles({
title: body.title,
description: body.description,
craetedat: body.craetedat,
createdby: body.createdby,
})
try {
const saveArticle = await newArticle.save();
res.json(saveArticle);
} catch (err) {
console.error(err.message);
}
});
And lastly here's the model schema:
import mongoose from "mongoose"
const Schema = mongoose.Schema;
const article = new Schema({
title: {
type: String,
required:true
},
description: {
type: String,
required: true
},
createdat: {
type: Date,
required: true,
default: Date.now
},
craetedby: {
type: String,
required: true
}
})
const Article = mongoose.model("Articles", article);
export default Article;
Thanks for your help in advance!