req.body value is undefined - node.js

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.

Related

Cannot Post to route

I am implementing a simple signup / login functionality in node js
But when using postman to post the router to localhost:3000/api/chatapp/register i am gettig error message
Cannot POST /api/register
CODE:
server.js
const express=require('express');
const mongoose=require('mongoose');
const cookiePaser=require('cookie-parser');
// const logger=require('morgan');
const app=express();
const dbConfig= require('./config/secret');
//adding middleware
app.use(cookiePaser()); //save our token in the cookie
// app.use(logger('dev')); // to display the url and http status code in the console
mongoose.Promise = global.Promise;
mongoose.connect(
dbConfig.url,{useNewUrlParser: true, useUnifiedTopology: true}
);
const auth=require('./routes/authRoutes');
app.use(express.json({limit: '50mb'})); //data coming in from form is limited up to 50 mb size
app.use(express.urlencoded({ extended: true, limit:'50mb'}));
app.use('/api/chatapp',auth);
app.listen(3000, () => {
console.log('Running on port 3000');
})
authRoute.js
const express=require('express');
const router=express.Router();
const AuthCtrl=require('../controllers/auth');
router.post('/register',AuthCtrl.CreateUser);
module.exports=router;
auth.js
module.exports={
CreateUser(req,res){
console.log(req.body);
}
};
userSchema.js
const mongoose = require("mongoose");
const userSchema = mongoose.Schema({
username: { type: String },
email: { type: String },
password: { type: String },
});
module.exports=mongoose.model('User',userSchema);
nodemon server and mongod are running fine
Postman result
for further details kindly look into my github repo :
https://github.com/Umang01-hash/chatApp-backend
Are you sure if that's the correct endpoint? Check out the folder structure and see this image for your answer.

Post request isn't working in node.js express/mongoose

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}`));

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?

Req.body works with POST req but not GET req. Using Body-Parser

I am able to store data in my mongoDB database using req.body in a POST request but I am not able to retrieve that data using req.body in a GET request. I can retrieve data if I pass a string but not req.body..
I have seen there are multiple posts on this issue in which body parser seems to solve the issue but I am still retrieving undefined even though I have body parser going.
Thanks in advance.
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const path = require('path');
const bodyParser = require('body-parser');
const PORT = process.env.PORT || 2000;
// app.use(express.urlencoded({extended: true}));
app.use(bodyParser.urlencoded({ extended: false }));
// app.use(express.json());
app.use(bodyParser.json());
app.use(express.static('public'));
const database = mongoose.connect('mongodb://localhost/users')
.then(() => console.log('connected to mongoDB!!'))
.catch((err) => console.error('unable to connect', err));
const userSchema = {
name: String,
email: String
}
const User = mongoose.model('User', userSchema);
app.post('/api/users',(req,res) => {
const user = new User({
name: req.body.name,
email: req.body.email
});
const create = user.save();
res.send('created a user account');
});
app.get('/api/users', async (req,res) => {
const find = await User
.find({ name: req.body.name});
console.log(find);
res.send(`your data is ${req.body.name}`);
})
app.listen(PORT, () => console.log(`listening on port ${PORT}`));
GET Resquest doesn't have a body. Instead you need to use query parameters.
You can do something like:
app.get('/api/users', async (req,res) => {
const find = await User
.find({ name: req.query.name});
console.log(find);
res.send(`your data is ${req.query.name}`);
})
To complement Leandro Lima's answer,
for route parameters:
app.get('/api/users/:name', async (req,res) => {
const find = await User
.find({ name: req.params.name});
console.log(find);
res.send(`your data is ${req.params.name}`);
})
The .../:name part makes up req.params.name (for example, .../:id then is req.params.id).
And for query parameters: /api/users/Dave?sex=male&developer=yes
Then req.queryhas {sex: 'male', developer: 'yes'}, thus could use req.query.sex and req.query.developer as you see fit.
Check out this question too: Node.js: Difference between req.query[] and req.params

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