0

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!

  • Yes that did answer it. i'm kinda confused why seen as express.urlencoded should have the same functionality. Or so I've heard. thanks for the help! – Petko Petkov Oct 23 '21 at 12:49

2 Answers2

0

Maybe you have a problem on using postman check if you are choosing JSON on postman body not text.

0

I found my mistake on the line where I set up the express middleware express.urlencoded in the server file I gave the wrong boolean value it should be as such:

app.use(express.urlencoded({    extended:false   }));