I'm facing an issue with sending data to my MongoDB database. When using router.post, my req.body appears empty. However, if I replace req.body
with the data from my send function like User(req.body)
, the data is successfully sent to MongoDB.
Below is the router code that I'm working with. The router.get
works perfectly, returning the database tables correctly on the /api
page:
const router = require("express").Router();
const User = require("./model/models");
const parser = require("body-parser").json();
router.get("/", async (req, res) => {
const data = await User.find({});
res.json(data);
});
router.post("/", parser, async (req, res) => {
console.log('1');
console.log(req.body);
console.log('2');
parser.v;
await User(req.body).save();
res.json({"msg": "ok"});
});
module.exports = router
Here is the code from my index.js
:
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const parser = require("body-parser").json();
var path = require('path');
app.use(express.urlencoded(true));
app.use(express.json());
app.use(parser);
app.use('/',require("./routes/routes"));
app.use(express.static(__dirname +'/public'));
app.use("/api", require('./data/api'));
app.listen(5000,function(){
console.log('server is alive')
})
This is the function I use for sending data:
const btn1 = document.getElementById('btnEnter');
let Login = "123";
btn1.addEventListener('click' ,e =>{
send({newsTxT : "someTextHere", newsZag: "someZag", author: "SomeAuthor"})
});
const send = async(body) => {
let res = await fetch("/api", {
method: "post",
header: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(body)
});
let data = await res.json();
console.log(data);
}