Mongoose: validation error path `name` is required - node.js

Here is my HTML with the form piece.
<form [formGroup]="form" (submit)="onSave()" *ngIf="!isLoading">
<mat-form-field>
<input matInput type="text" formControlName="name" placeholder="Organization Name">
Here is the code for onSave() from my component.ts file.
onSave() {
if (this.form.invalid) {
return;
}
this.isLoading = true;
if (this.mode === "create") {
this.objsService.add(
this.form.value.name
);
} else {
this.objsService.update(
this.id,
this.form.value.name
);
}
this.form.reset();
}
Here is the add() function from my service.
/* #region Create of CRUD */
add(name: string) {
const objData = new FormData();
objData.append("name", name);
this.http
.post<{ message: string; obj: Organization }>(
'http://localhost:3000/api/organizations',
objData
)
.subscribe(responseData => {
this.router.navigate(["/organizations"]);
});
}
/* #endregion */
And lastly here is my .post to the router in mp api.
/* #region Create of CRUD */
router.post('', (req, res, next) => {
console.log('req.body.name: ' + req.body.name);
const obj = new objModel({
name: req.body.name
});
obj.save().then(createdObj => {
res.status(201).json({
message: capitalize(plural) + ' added successfully',
obj: {
...createdObj,
id: createdObj._id
}
});
});
});
/* #endregion */
As you can see in my api I''m running "console.log('req.body.name: ' + req.body.name);", it's output is "req.body.name: undefined". How could this be? What am I missing?
In my service I ended up add the following line.
add(name: string) {
const objData = new FormData();
objData.append('name', name);
console.log(name);
console.log(objData);
Here's what showed up in the console.
dfgasdfg
FormData {}
__proto__: FormData
append: ƒ append()
...
values: ƒ values()
arguments: (...)
...
name: "values"
__proto__: ƒ ()
...
name: ""
name: "" should be name: "dfgasdfg". Is the .append syntax incorrect?
Here's my server.js file. I did include body-parser. Did I implement it improperly?
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const postsRoutes = require("./routes/posts");
const organizationsRoutes = require("./routes/organizations");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Thank you in advance!

i think you missing body-parser middleware in node api that's why you getting undefined in req.

const bodyParser = require('body-parser');
const app = express();
app.use(express.json());
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
please try to use above express middleware in server.js root file, to get data in req.body object.

Ok, I'm an idiot. I needed to use the following.
app.use(bodyParser.urlencoded({extended: true}));
I was using:
app.use(bodyParser.urlencoded({extended: false}));
Thanks for the direction!!!!
P.S.
Ok, I take it back. It wasn't a permanent fix. I am running express 6.9.0, doesn't express 4.16+ have it's own parser? I changed my code to now have this:
app.use(express.json());
app.use(express.urlencoded());
In my route for the API it looks like it's still not populating req.body.name with the value from the form.
Using this:
console.log('req.body.name: ' + req.body.name);
I get this:
req.body.name: undefined

Related

req.body value is undefined

My req.body shows {} always even though I am using body-parser in my code
user model
const userSchema = new mongoose.Schema({
email: {
type: String,
required:true,
index:true,
},
password: {
type: String,
required: true
}
},{timestamps:true});
module.exports = mongoose.model('User', userSchema);
routes
const express= require('express');
const router = express.Router();
const {currentUser} = require("../controllers/user");
router.post('/current-user', currentUser);
module.exports = router;
Controllers
const User = require("../models/user");
exports.currentUser = async (req, res) => {
const {email} = req.body
console.log(email)
// console.log(req.query)
await User.findOne({email}).then((user) => {
if (!user) {
// console.log(user);
return res.status(401).json({
error: 'User not found!'
});
}
res.json({
data:"SUCCESS"
})
})
}
I am getting an error: user not found even if the email id exists.
If I console.log(req.body)
=> Output:
{}
console.log(req.body.email)
=> Output:
undefined
Please help me fix this.
You might want to use bodyPrser() middleware.
You can read more about it here
npm i body-parser --save
Then, in your server.js or app.js file
const bodyParser = require('body-parser');
const app = express();
app.use(router()); //your user defined router middleware
app.use(bodyParser.json()); //this is a bodyparser middleware to read/extract the
//data from req.body
Please dont use body parser its already deprecated, since you are already using express there is a built in middleware for body-parser like
const app = express()
app.use(express.json({ limit: '50mb' }))
app.use(express.urlencoded({ limit: '50mb', extended: true, parameterLimit: 50000 }))
this will do work of body-parser.
Other thing, can you tell us what are you sending in request since it is a post request and you might be sending an empty object thats why you are getting {} in req.body?
I can see you are extracting email from it but if you can provide sample request, it will definitely help.

express nodejs body is empty after post request

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),
})

Node: req.body is undefined

I am trying to access the things that I send from req.body in nodejs but it always comes as undefined I have tried using body-parser still it shows undefined.
Here is my code:
const express = require ('express');
const app = express();
var bodyParser = require("body-parser");
var cors = require('cors');
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.use(cors());
app.post('/api/parts', (req, res) =>{
console.log('In app.post with id:'+ req.body.id + ' name:'+ req.body.name); // shows undefined in id and name
const part= parts.find(c=>c.id === parseInt(req.body.id));
if(!part) {
console.log('part not found and to be inserted/pushed -current lenght:'+ parts.length);
const p= { id:parseInt(req.body.id), name:req.body.name};
parts.push(p);
console.log('parts lenght:'+ parts.length);
console.log(parts);
res.send(parts[parts.length-1])
}
else {
console.log('Part with ID '+ req.body.id+ ' exists already');
res.status(404).send('Part with ID '+ req.body.id+ ' exists already')
}
})
Here is my postman Body:
{
"id":1,
"name":"abcd"
}

API posts x-www-form-urlencoded data but fails on json

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?

Axios post request.body is empty object

I am trying to post data from my react. Backend - express.
Here is backend code:
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
var methodOverride = require("method-override");
var mongoose = require("mongoose");
var expressSanitizer = require("express-sanitizer");
mongoose.connect("mongodb://localhost/blog-react");
//app config
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
//must be after parser
app.use(expressSanitizer());
app.use(methodOverride("_method"));
//schema config
var blogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
//it should be date. With default value now.
created: {
type: Date, default: Date.now
}
});
var Blog = mongoose.model("Blog", blogSchema);
function handle500(response, error){
console.log(error.stack);
response.status(500);
response.json({error: "error: internal server error"});
}
app.post("/api/blogs", function(request, response){
var blog = {
title: request.sanitize(request.body.title),
image: request.sanitize(request.body.image),
body: request.sanitize(request.body.body)
};
console.log(request.body);
Blog.create(blog, function(error, newBlog){
if(error){
console.log("inside post handler ERROR")
handle500(response, error);
}
else{
console.log("inside post handler OK")
response.json({status: "success"});
}
});
});
React code:
var requestUrl = "/api/blogs";
var blog = {
title: "a",
image: "b",
body: "c"
}
axios.post(requestUrl, blog)
.then(function(response){
console.log("success",response.data)
})
.catch(function(response){
console.log("error", response);
});
When I post data via axios - request.body is always {}
But if I post data via regular form - all is correct - request.body contains all expected data.
What am I doing wrong with axios?
You are missing one middleware, bodyParser.json(). Add it to your configuration.
mongoose.connect("mongodb://localhost/blog-react");
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.json()); // <--- Here
app.use(bodyParser.urlencoded({extended: true}));
For people using Express>=4.16, bodyParser has been changed to the following:
app.use(express.json());
For me the issue was valid JSON format including double quotes on the variables.
This did not work
const res = await axios.post(serverPath + "/user/login", {
email: email,
password: password,
});
This DID work (with double quotes around email and password)
const res = await axios.post(serverPath + "/user/login", {
"email": email,
"password": password,
});
It looks like you only have two points left to make it work :
one : the http method should be set to POST instead of GET since you want to send something.
two : you can then add the http header (like what you did with the authorization header) Content-Type: 'application/json`
On the back-end don't forget to use some kind of body parser utility package like this one : body-parser and set it up with your app.
I suppose your server is using express, here is how you will do it with express :
const express = require('express');
const app = express();
const bodyParser = require('body-parser')
const jsonParser = bodyParser.json();
app.use(jsonParser); // use it globally
app.get('your_route', jsonParser, otherMiddleware, (req, res) => ...); // use it for specific routes
/* ... rest of your code */

Resources