status : 500 Internal Server Error postman only posts empty curly brackets when enter the data on the body - javascript

and this is my code (index.js), (auth.js)
const express = require("express");
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const authRoute = require("./routes/auth");
const app = express();
dotenv.config();
app.use(express.json());
mongoose.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
}).then(console.log("Connected to MongoDB"))
.catch((err) => console.log("err"));
app.use("/api/auth",authRoute );
app.use("/api/auth",authRoute);
app.listen("3000", () => {
console.log("Backend is running.");
});
const router = require("express").Router();
const User = require("../models/User");
//REGISTER
router.post("/register", async (req, res) => {
try {
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password,
});
const user = await newUser.save();
res.status(200).json(user);
} catch (err) {
res.status(500).json(err);
}
});
//LOGIN
module.exports = router;
and image of the postman result
when I send the request postman posts empty curly brackets. I want to get the post data on the down of the body at the postman
screenshot of the postman
and this is what terminal logs
result on the terminal

You should check what receives in user object at const user = await newUser.save();
data would be in user.data
or use json instead,
const user = await newUser.save();
res.status(200).jsonp(user);

.env file must be inside the root folder, not the outside

I got that error in postman and my problem was that I was adding a str data in an int field in pgAdmin

Related

Exporting Multiple Objects Stops My HTML Requests from being processed

I have some simple javascript code in three files. There is my server.js, which has
const userRouter = require('./routes/users')
app.use("/",userRouter)
Then there is my middleware users.js with
module.exports = router
and lastly user.js with
module.exports = {
User:User,
validateLogin:validateUserLogin,
validateRegister:validateUserRegister,
}
When my user.js had just the export line module.exports = User my code worked just fine. server.js imports users.js, which imports user.js. But when exporting functions along with my User object, my requests stop working. Why? How can I fix this? I'm using Node.js with express and mongo db. All my HTML requests are in users.js.
The code to my server.js is
const express = require('express');
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
//just show server is running
const app = express()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const PORT = 4000;
app.get("/status", async (req, res) => {
return res.status(400).send("server for GET is running");
});
app.post("/status", async (req, res) => {
return res.status(200).send({
status: "server for POST is running",
message: req.body.message
});
});
app.listen(PORT, function() {
console.log(`server running on port ${PORT}`);
});
const url = "mongodb+srv://Admin:strongpassword#cluster0.tjual.mongodb.net/ConfusedTom?retryWrites=true&w=majority"
mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: "ConfusedTom"
}).then(() => {
console.log("connected successfully to server, using database %s\n", mongoose.connection.$dbName);
}).catch(err => {
console.log(err);
});
const userRouter = require('./routes/users')
app.use("/",userRouter)
and here is my users.js
const mongoose = require("mongoose");
const express = require("express");
const router = express.Router();
const ObjectId = mongoose.Types.ObjectId;
const Review = require("../models/review.js")
const TVShow = require("../models/tvshows.js")
const { User, validateLogin, validateRegister} = require("../models/user.js")
router.get("/username", async (req, res) => {
console.log("reached!")
var user = await User.findOne({ username: req.body.username });
if (!user) return res.status(400).send("User doesn't exist.");
return res.status(200).send(user)
});
router.post("/register", async(req,res) => {
const { error } = validateRegister(req.body);
if (error) return res.status(400).send(error.details[0].message);
else user = await User.findOne({ username: req.body.username });
if (user) return res.status(400).send("Username already taken.");
//create new user
user = new User({
firstName: req.body.firstName,
lastName: req.body.lastName,
username: req.body.username,
password: req.body.password,
});
user.save();
return res.status(200).send("User registered successfully.");
})
router.post("/login", async (req, res) => {
console.log("reached!")
// validate the request body first
const { error } = validateLogin(req.body);
if (error) return res.status(400).send(error.details[0].message);
//find an existing user
var user = await User.findOne({ username: req.body.username });
if (!user) return res.status(400).send("Username reqired.");
if (user) {
if (user.validatePassword(req.body.password)) {
return res.header.status(200).send("User login successfully");
}
else return res.status(400).send("Password is incorrect");
} else return res.status(400).send("User doesn't exist.");
});
module.exports = router
The problem with your updated import of the stuff from user.js is you're using the wrong names for the functions. You currently have:
const UserStuff = require("../models/user.js")
const User = UserStuff.User;
const validateLogin = UserStuff.validateUserLogin;
const validateregister = UserStuff.validateUserRegister;
but the object you're exporting is:
module.exports = {
User:User,
validateLogin:validateUserLogin,
validateRegister:validateUserRegister,
}
You're using the wrong names of the functions (validateUserLogin instead of validateLogin). The names you use have to match at both ends. So:
const UserStuff = require("../models/user.js")
const User = UserStuff.User;
const validateLogin = UserStuff.validateLogin;
// ^^^^^^^^^^^^^
const validateregister = UserStuff.validateRegister;
// ^^^^^^^^^^^^^^^^
or more concisely:
const { User, validateLogin, validateRegister} = require("../models/user.js")

Express 4.17.1 req.body returns undefined

The code is split into 2 files:
the main file: server.js
the router file: user.js
In the user.js file req.body returns undefined and doesn't save the data to database
The data sent to /user/register returns 'Could not save to database'.
I've tried bodyParser.json() and bodyParser.urlencoded({extended: true}), although it isn't required in express 4.17.x, and they do not work.
Other common solutions like app.use(express.json()) also didn't help.
server.js
const express = require('express')
const mongoose = require('mongoose')
const User = require("./models/userSchema");
const userRouter = require('./routes/user')
const placeRouter = require('./routes/place');
const bodyParser = require('body-parser');
const app = express()
const PORT = 5000
app.use(express.json())
mongoose.connect('mongodb://localhost:27017/instaDB', {
useNewUrlParser: true,
useUnifiedTopology: true
}, () => {
console.log('Connected to Database');
})
app.use('/user', userRouter)
app.listen(PORT, ()=>{
console.log(`Listening on PORT: ${PORT}`);
})
user.js
const express = require('express')
const User = require("../models/userSchema");
userRouter = express.Router()
userRouter.post('/register', (req, res) => {
const {username, password} = req.body
console.log(req.body.username);
console.log(password);
User.findOne({username}, (err, user) => {
if(err){
res.status(500).json({
err: true,
msgBody: 'Server Error'
})
} if(user){
res.status(400).json({
err: true,
msgBody: 'Username already exists'
})
}
else{
const newUser = new User({
username,
password
})
newUser.save((err)=>{
if(err){
res.status(500).json({
err: true,
msgBody: 'Could not save to database'
})
} else {
res.status(200).json({
err: false,
msgBody: 'Registered Successfully'
})
}
})
}
})
})
module.exports = userRouter;
I would guess the initial request lacks the header Content-Type: application/json.
So Express json parser ignores the request body as it is not typed as json.
So the parser does not fill the req.body field.
Try adding this header with this value (Content-Type: application/json) to your request.
How you will do that depends on how you send this request (curl, postman, javascript xhr, react/angular..., lib...)

MongoDB Returns Empty Error Object when Making POST Request

I'm currently learning about APIs. I'm using Dev Ed's video on a RESTful MERN API. I set up my routes and I could successfully connect to my MongoDB database. However, when attempting to call save() on a post to the DB, I was returned my error message, a JSON object with a message containing the err, but my err object was completely empty.
posts.js:
const express = require('express');
const router = express.Router();
const Post = require('../models/Post');
router.get('/', (req, res) => {
res.send('We are on /posts!');
});
router.post('/', (req, res) => {
const post = new Post({
title: req.body.title,
desc: req.body.desc,
});
post.save()
.then(data => {
res.json(data);
})
.catch(err => {
res.json({ message: err });
});
});
module.exports = router;
app.js:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv/config');
const app = express();
const PORT = 8080;
app.use(bodyParser.json());
// Import Routes ------------------------
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);
// ROUTES --------------------------------
app.get('/', (req, res) => {
res.send('We are home!');
});
mongoose.connect(
process.env.DB_CONN,
{ useNewUrlParser: true },
() => {
console.log('Succesfully connected to DB!')
});
app.listen(PORT);
Post.js (schema):
const mongoose = require('mongoose');
const PostSchema = mongoose.Schema({
title: {
type: String,
required: true,
},
desc: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
}
});
module.exports = mongoose.model('Posts', PostSchema);
My POST request and response (Postman):
In my code, I am attempting to send the new Post to my DB, but instead I get an error, an empty one. I either need to figure out how to view my error correctly (so that's it's not empty) or the larger problem: why my POST request is failing.
Again, I am learning about APIs, this is my very first time writing one. If there's anything I missed (like other code that you would need) or if there's something I should be doing differently, please, let me know! Thank you in advance!
use status when you want to use res like this:
for success result
res.status(200).json(data);
for .catch
res.status(500).json({ message: err });
but I prefer use async/await with try/cacth like this:
router.post('/', async(req, res) => {
const post = new Post({
title: req.body.title,
desc: req.body.desc,
});
try {
let data = await post.save()
res.status(200).json(data)
} catch (error) {
res.status(500).json({ message: error});
}
});
check the documentation of promises in mongnoos
check the connection of mongoose like this:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv/config');
const app = express();
const PORT = 8080;
app.use(bodyParser.json());
// Import Routes ------------------------
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);
// ROUTES --------------------------------
app.get('/', (req, res) => {
res.send('We are home!');
});
runMongoose()
app.listen(PORT);
async function runMongoose(){
try {
await mongoose.connect(
process.env.DB_CONN,
{ useNewUrlParser: true }
);
console.log("mongodb is OK");
} catch (error) {
console.log("mongodb Warning", error);
}
}
if Succesfully connected to DB! printed mongoose connection is OK
the problem is that you added
{ useNewUrlParser: true }
remove that and it's gonna work fine ;)

Why the user = await User.findOne({ email }) returns null?

I'm setting up a login route and I decided to test it with postman and it worked but later when I was checking my DB configuration I found an error when I fixed the error the login test on postman doesn't work
so in my server.js file I have :
const express = require("express");
const connectDB = require("./config/db");
const app = express();
// Connect to MongoDB
connectDB();
// Initialize middleware
app.use(express.json());
// Define routes
app.use("/api/users", require("./routes/users"));
app.use("/api/auth", require("./routes/auth"));
app.use("/api/posts", require("./routes/posts"));
app.use("/api/profile", require('./routes/profile'));
// Create server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
The connectDB function in config/db.js :
const mongoose = require("mongoose");
require('dotenv').config()
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
});
console.log("Successfully connected to MongoDB");
} catch (err) {
console.error(err.message);
}
};
module.exports = connectDB;
In the auth.js route :
const express = require("express");
const router = express.Router();
const { check } = require("express-validator");
const {auth} = require('../middlewares/auth');
const {login} = require('../controllers/authController');
// #route: POST api/auth
// #desc: Login
// #access: Public
router.post("/",
[
check("email", "Email is required").not().isEmpty(),
check("password", "Password is required").not().isEmpty(),
],
login
);
module.exports = router;
The Auth controller in controllers/authController.js :
const { validationResult } = require("express-validator");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
require('dotenv').config()
exports.login = async (req, res) => {
try {
// Check for validation errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Check if user exists
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ msg: "Invalid credentials : you must register" });
}
// If exists, check password
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(400).json({ msg: "Invalid credentials : wrong password" });
}
// Return jwt
const payload = {
user: {
id: user.id,
},
};
jwt.sign(payload,
process.env.JWT_SECRET,{expiresIn: 3600},(err, token) => {
if (err) throw err;
res.json({ token });
}
);
} catch (err) {
console.error(err.message);
res.status(500).send("There was an error with the server. Try again later.");
}
}
Everything looks great and when I try to login with postman it returns the "Invalid credentials : you must register" message from this code in authController.js ( when I console.log(user) it returns null ) :
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ msg: "Invalid credentials : you must register" });
}
PS: At first, in the db configuration I forgot to add the mongo client options and everything worked and it returns the token in postman but after fixing the error I had the login problem

Postman returns ' Could not get any response '

Postman returns ' Could not get any response ' when I send a Post request, but get a request to other URL works just fine. please how can I resolve this issue? index.js is the entry point to my application. the get URL below is working.
index.js
const express = require('express')
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const bodyParser = require('body-parser')
const app= express()
//body parser
app.use(bodyParser.json())
//config
dotenv.config()
//connect to db
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true },
()=>{
console.log('contented to db')
}
)
//import route
const authRoute = require('./ROUTES/auth')
app.use('', authRoute)
app.use('/api/user', authRoute)
//start server
app.listen(5000);
# auth.js #
all routings are done in auth.js
const express =require('express')
const router = express.Router();
const User = require('./moduls/User')
router.get('/',(req, res)=>{
res.send('home')
})
//validation schema
const joi =require('#hapi/joi');
const regSchema ={
name:joi.string().min(6).required(),
email:joi.string().required().email(),
password:joi.string().min(8).required()
}
router.post('/register', async(req, res)=>{
//check and return error status
const { error } = joi.ValidationError(regSchema);
if(error) return res.status(400).json({message: err})
const emailExist = await User.findOne(req.body.email)
if (emailExist) return res.status(400).json({message:'there is a user with this email'})
//get user object
const user =new User({
name:req.body.name,
email:req.body.email,
password:req.body.password,
rePassword:req.body.rePassword
})
try{
await user.save()
.then(data=>{
res.json(data)
})
}
catch(err){
res.status(400).json({message: err})
}
})
module.exports=router;
modules/User.js
user module in the modules folder
const mongoose = require('mongoose')
const userSchema =new mongoose.Schema({
name:{
type: String,
required:true,
min:6,
max:30
},
email:{
type: String,
required:true,
max:100
},
password:{
type:String,
required:true,
min:8
},
rePassword:{
type:String,
required:true,
min:8
},
date:{
type:Date,
default:Date.now()
}
})
module.exports = mongoose.model('User', userSchema)
The .save() function returns a promise that you can await. You don't need to use .then() when using async/await.
Instead of this.
await user.save()
.then(data=>{
res.json(data)
})
I'd do this.
const data = await user.save();
res.json(data);

Categories

Resources