I have tried all out there but still the post request is giving me an empty. I checked in browser and also in postman the values are sent via the payload, but when getting via the router post, req.body is empty
main
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
// var bodyParser = require("body-parser"); body parser also didnt work
const app = express();
// app.use(
// bodyParser.urlencoded({
// extended: true,
// })
// );
// app.use(bodyParser.json());
app.use(cors());
app.use(express.urlencoded({ extended: true })); // interchanged this below express.json didnt work
app.use(express.json());
const PORT = 3009;
// import routes
const router = require("./routes/route");
app.use("/api", router);
// connect mongo start
const uri =
"mongodb+srv://adminuser:password#cluster0.gtkdj.mongodb.net/mydb?retryWrites=true&w=majority";
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
mongoose.connect(uri, options);
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function () {
console.log("Mongo Connected");
});
app.listen(PORT, () => {
console.log("Port is connected at ", PORT);
});
model
const mongoose = require("mongoose");
const dataSchema = mongoose.Schema({
name: {
type: String,
},
});
const dataModel = mongoose.model("data", dataSchema);
module.exports = dataModel;
routes
const express = require("express");
const router = express.Router();
const dataModel = require("../model/schema");
router.post("/new_items", (req, res) => {
const data = new dataModel({
name: req.body.name,
});
console.log(data, req.body);
data
.save()
.then((item) => res.send(item))
.catch((err) => res.status(400).send(err));
});
console output { _id: 6022f0c0b3dd8f2sdc5302f9 } {}
The req body is empty. Please help me on this. Thanks
The codes were correct. But, the post request header was not present. After passing the header, it worked as intended.
await fetch("http://localhost:3009/api/new_items/", {
method: "POST",
headers: {
"Content-Type": "application/json", // this was missing
},
body: JSON.stringify(body),
})
Related
I want to update a post in my bdd with the new value. When i click for validate i have an empty req.body!
exports.updatePost = (req, res, next) => {
Post.update(
{
message: req.body.message,
},
{ where: { id: req.params.id } }
)
.then(() => res.status(200).json({ message: "post modifié" }))
.catch((error) => res.status(500).json({ error }));
console.log(req.body)
console.log(req.params.id)
};
As you can see i console log my req.body for check, my req.paramas.id give me the right thing. Since i have this problem i decided to check my post route and my app.js but i didn't see anything.
my route is like this:
const express = require("express");
const router = express.Router();
const postCtrl = require("../controllers/post");
const auth = require("../middleware/auth");
const multer = require("../middleware/multer-configs");
//DIFFERENTE ROUTES POUR LES POSTS, COMPRENNANTS LES DIFFERENTS MIDDLEWARE UTILES ET D'AUTHENTIFICATION
router.get("/", auth, postCtrl.getAllPost);
router.post("/", auth, multer, postCtrl.createPost);
router.delete("/:id", auth, postCtrl.deletePost);
router.put("/:id", auth, postCtrl.updatePost);
router.get("/:id", auth, postCtrl.getPostByUserId);
module.exports = router;
and my app.js is like this:
const express = require("express");
require("dotenv").config();
const helmet = require("helmet");
const cors = require("cors");
const db = require("./models");
const path = require("path");
const bodyParser = require("body-parser");
const userRoutes = require("./routes/user");
const postRoutes = require("./routes/post");
const likeRoutes = require("./routes/like");
const commentRoutes = require("./routes/comment");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//MODULE C.O.R.S
app.use(cors());
app.use(express.urlencoded({ extended: true }));
// POST
app.use("/api/post", postRoutes);
I don't really understand why my backend can't see the back or don't give me the result of my body.
my client side is like this actually:
const updatePost = () => {
if (textEdit) {
const data = new FormData();
data.append("message", textEdit);
axios.put(`http://localhost:5000/api/post/${id}`, data, {
headers: {
Authorization: `Bearer ${sessionStorage.getItem("authToken")}`,
},
})
.then((res) => {
console.log(res);
console.log(id)
console.log(message)
console.log(textEdit)
})
}
}
I am learning nodeJs. I am using mongoDB atlas database to perform the operations. I want to insert the user data but its not inserting into a collection.
Using postman i got 200 in response and "message :{} " My code is below please check and provide any solution.
index.js
const express = require('express');
const bodyParser = require("body-parser");
const mongoose = require('mongoose');
require('dotenv/config');
const Tea = require('./models/tea')
const app = express();
app.use(express.json());
var fs = require("fs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
try {
mongoose.connect("mongodb+srv://test:<test>#firstcluster.g9kk1.mongodb.net/glocoach?retryWrites=true&w=majority",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}, (req, res) => {
console.log("Connection Successfull!!");
});
} catch (error) {
console.log("Connection error");
}
app.post('/login', async (req, res)=> {
try{
const userTea = new Tea(req.body);
await userTea.save();
res.send(userTea);
}catch(error){
console.log();
res.send({
message : error
})
}
})
app.listen(3000, ()=> {
console.log("Listening to 3000");
});
models/tea.js
const mongoose = require("mongoose"); //import mongoose
// tea schema
const TeaSchema = new mongoose.Schema({
name: {type:String, required:true},
age : Number
});
const Tea = mongoose.model('Tea', TeaSchema); //convert to model named Tea
module.exports = Tea; //export for controller use
postman
if i don't use the "userTea.save()" method
then i got response in postman in console but still data is not inserted - ?
try{
const userTea = new Tea(req.body);
// await userTea.save();
res.send(userTea);
console.log(req.body);
}
I have a route to create a category and when I try to run it in postman it returns an error saying, "Cannot POST /api/category"
I have tried to run through my code again and again but I cannot see where is the problem.
Thank for your help in advance
My schema:
const mongoose = require("mongoose");
const CategorySchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "user",
},
categoryName: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = Categories = mongoose.model("category", CategorySchema);
My route:
const express = require("express");
const router = express.Router();
const auth = require("../../middleware/auth");
const { check, validationResult } = require("express-validator");
const Category = require("../../models/Category");
// #route POST api/category
// #desc Create or update users category
// #access Private
router.post(
"/",
[auth, [check("categoryName", "Category name is required").not().isEmpty()]],
async (req, res) => {
console.log(categoryName);
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
}
);
module.exports = router;
this is the way my code is organized
Ok thanks to Molda I found the problem.
I was missing my route definition in my server.js file.
All good now, thank you for your help.
const express = require("express");
const connectDB = require("./config/db");
const app = express();
//Connect DB
connectDB();
// Init Middleware
app.use(express.json({ extended: false }));
app.get("/", (req, res) => res.send("API Running"));
// Define routes
app.use("/api/users", require("./routes/api/users"));
app.use("/api/auth", require("./routes/api/auth"));
app.use("/api/profile", require("./routes/api/profile"));
app.use("/api/category", require("./routes/api/category"));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
I'm Unable to store the data from node.js to mongoDB atlas below are the code snippets.
Below is the app.js code where i established the mongodb connection.
const express = require("express");
var app = express();
const bodyparser = require("body-parser");
const cors = require("cors");
const Post=require("./models/post");
const mongoose=require("mongoose");
app.use(bodyparser.urlencoded({ extended: false }))
app.use(bodyparser.json())
app.use(cors());
app.post('/sms', function (req, res) {
let obj=JSON.parse(req.body.user);
const user= new Post({
userName:obj.userName,
password:obj.password,
email:obj.email,
address:obj.address
})
user.save()
.then(data => {
res.json(data),
res.status(200).json({data})
})
.catch(err => {
res.json(err)
});
})
mongoose.connect("mongodb+srv://srihari:srihari#cluster0-yuykq.mongodb.net/srihari?retryWrites=true&w=majority",{useNewUrlParser:true,useUnifiedTopology:true},()=>{
console.log("DB connected!");
})
app.listen(8080);
Below is the code of Schema to bind the data which is coming from frontend.
const mongoose = require("mongoose");
const postschema=mongoose.Schema({
userName:{
type:String
},
password:{
type:String
},
email:{
type:String
},
address:{
type:String
},
});
module.exports = mongoose.model('Posts',postschema)
Try using Async/Await functions when storing/retrieving data in mongodb;
const express = require("express");
var app = express();
const bodyparser = require("body-parser");
const cors = require("cors");
const Post=require("./models/post");
const mongoose=require("mongoose");
app.use(bodyparser.urlencoded({ extended: false }))
app.use(bodyparser.json())
app.use(cors());
app.post('/sms', async function (req, res) {
let obj=JSON.parse(req.body.user);
const user= new Post({
userName:obj.userName,
password:obj.password,
email:obj.email,
address:obj.address
})
await user.save()
.then(data => {
res.json(data),
res.status(200).json({data})
})
.catch(err => {
res.json(err)
});
})
mongoose.connect("mongodb+srv://srihari:srihari#cluster0-yuykq.mongodb.net/srihari?retryWrites=true&w=majority",{useNewUrlParser:true,useUnifiedTopology:true},()=>{
console.log("DB connected!");
})
app.listen(8080);
It's because you are using Schema directly. First you have to define it like below.
const Schema = mongoose.Schema ;
Write above line of code after you imported the mongoose.
I have a basic Mongo API.
During testing, I can easily post data with postman when it is x-www-form-urlencoded but when I use raw JSON, it is just blank.
I stored the body to see what was the difference and noticed that while using the x-www-form-urlencoded format there was data but when using JSON, my object was blank and doesn't post anything.
The data schema is as follows:
var mongoose = require('mongoose');
// Setup schema
var testSchema = mongoose.Schema({
fieldone: {
type: String,
required: true
},
fieldtwo: {
type: String,
required: true
},
fieldthree: {
type: String,
required: true
},
fieldfour: String,
fieldfive: String,
fieldsix: String
});
// Export model
var test= module.exports = mongoose.model('test', testSchema);
module.exports.get = function(callback, limit) {
test.find(callback).limit(limit);
}
The controller is as below:
// Controller.js
// Import model
Test= require('./Model');
// insert new test
// Handle create actions
exports.new = function(req, res) {
const {
fieldone,
fieldtwo,
fieldthree,
fieldfour,
fieldfive,
fieldsix
} = req.body
var test= new Test(req.body);
// console log for testing if the data shows
console.log(test)
// save and check for errors
test.save(function(err) {
// if (err)
// res.json(err);
res.json({
message: 'New test created!',
data: test
});
});
};
Below is my api-routes
// api-routes.js
// Initialize express router
const router = require('express').Router();
// Set default API response
router.get('/', function(req, res) {
res.json({
status: 'alls good',
message: 'alls good',
});
});
// Import controller
const testController = require('./Controller');
// routes
router.route('/test')
.get(testController.index)
.post(testController.new);
// Export API routes
module.exports = router;
Below is my index.js:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors')
const app = express();
// Import routes
var apiRoutes = require("./api-routes");
var corsOptions = {
origin: '*',
credentials: true
};
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/api', apiRoutes);
// mongo con
mongoose.connect('mongodb://localhost/mongodojo', { useNewUrlParser: true
});
var db = mongoose.connection;
// error check
if (!db)
console.log("Error while connecting")
else
console.log("connection successful")
// Setup server port
const port = process.env.PORT || 3000;
app.get('/', (req, res) => res.send('Welcome'));
Is there anything in my code that could be causing this?