Postman returns ' Could not get any response ' - javascript

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

Related

Cannot GET / error using thunderclient to send request

I'm having trouble with my server routes. is there any problem with my routes? or a problem with the code?
I have checked all the possible question answers.
I'm having trouble with my server routes.
used thunderclient to send request
when I route it shows this
enter image description here
I tried to set thunder client POST to GET but got the same error
Index.js
const connectToMongo = require('./db');
const express = require('express')
connectToMongo();
const app = express()
const port = 5000
//Available Routes
app.use('/api/auth', require('./routes/auth'))
// app.use('./api/notes', require('./routes/notes'))
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
my auth.js where login and register exist.
const express = require('express');
const User = require('../models/User');
const router = express.Router();
const { body, validationResult } = require('express-validator');
// Create a User using: POST "/api/auth/". Doesn't require auth
router.post('/',[
body('name').isLength ({min: 3}),
body('email').isEmail(),
body('password').isLength ({min: 5})
], (req, res)=>{
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send(req.body);
})
module.exports = router
my user.js which shows user data
const mongoose = require('mongoose');
const {Schema}= mongoose;
const UserSchema = new Schema({
name:{
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password:{
type: String,
required: true
},
date:{
type: Date,
default: Date.now
},
});
module.exports = mongoose.model('user', UserSchema);

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

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

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")

Why is this error displaying 'Illegal arguments: undefined, string'?

I am building a simple node.js app. I build my backend api for user registration. I am trying to test it with postman and i am having this error 'Illegal arguments: undefined, string'. What could be responsible for this?. Relevant codes are supplied below
User Schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema
const UserSchema = new Schema({
userName: {
type: String,
required: true,
unique: true
},
firstName: {
type: String,
},
lastName: {
type: String,
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
dateOfRegistration: {
type: Date,
default: Date.now
},
dateOfBirth: {
type: Date,
},
userCategory: {
type: String,
default: 'workingClass'
}
})
module.exports = mongoose.model('users', UserSchema)
The problem has been solved. Postman was sending the request as in 'text' format instead of 'JSON' format and as such the backend couldn't make sense of data. Every worked fine when changed the settings on my Postman from 'text' to 'JSON'.
controller
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const config = require('config');
const auth = require('../middleware/auth')
const { check, validationResult } = require('express-validator');
const User = require('../models/User');
const UserModel = require('../models/User');
// #route POST api/users, Register a users; access Public
router.post('/', [
check('userName', 'Please add user name').not().isEmpty(),
check('email', 'Please include a valid email').isEmail(),
check('password', 'Please enter a password with six or more characters').isLength({ min: 5 })
],
async (req, res) => {
const errors = validationResult(req);
if(!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { userName, firstName, lastName, email, password, dateOfBirth, dateOfRegistration, userCategory } = req.body;
try {
let user = await User.findOne( { email });
if (user) {
return res.status(400).json({ msg: 'User already exist'})
}
user = new User({
userName,
firstName,
lastName,
email,
password,
dateOfBirth,
dateOfRegistration,
userCategory
});
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
const payload = {
user: {
id: user.id
}
}
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error')
}
}
);
module.exports = router;
server.js
const express = require('express');
const mongoose = require('mongoose');
const path = require('path');
// api require routes
const users = require('./routes/users');
// const auth = require('./routes/auth');
// const students = require('./routes/studentsSub');
// const workers = require('./routes/workersSub');
const app = express();
// database connection
const connectDB = async () => {
try {
await mongoose.connect('mongodb+srv://nawill:usha0816#cluster0.77u0d.mongodb.net/myFirstDatabase?retryWrites=true&w=majority',
{
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
});
console.log('MongoDB Connected ...')
} catch (err) {
console.error(err.message);
process.exit(1);
}
};
connectDB();
//Middleware
app.use(express.json({ extended: false }));
// app.get('/', (req, res) => res.json ({ msg: 'Hello node project'}));
//Routes
app.use('/api/users', users );
// app.use('/api/auth', auth );
// app.use('/api/students', students );
// app.use('/api/workers', workers );
//Start Server
app.listen(3000, ()=> console.log("Server started on 3000"))

node.js req.body returning undefined

EDIT: #LawrenceCherone solved this, its (req, res, next) not (err, res, req)
I am creating a MERN app (Mongo, express, react, node).
I have some routes that work fine and return data from mongodb. However I created a new controller to access a separate collection and whenever i try to create a new document in it my req.body returns undefined.
I have setup my server.js like this:
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const connectDB = require("./db");
const app = express();
const apiPort = 3000;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
app.use(bodyParser.json());
connectDB();
app.use("/api", require("./routes/router"));
var server = app.listen(apiPort, () => console.log(`Server running on port ${apiPort}`));
module.exports = server;
My router looks like this:
const express = require("express");
const QuizController = require("../controllers/quiz-controller");
const UserController = require("../controllers/user-controller");
const router = express.Router();
// quiz routes
router.post("/quizzes", QuizController.createQuestion);
router.get("/quizzes", QuizController.getAllQuestions);
router.get("/quizzes/:quiz_name", QuizController.getQuestionsByQuiz);
router.get("/quizzes/questions/:question_id", QuizController.getQuestionById);
router.put("/quizzes/:question_id/edit", QuizController.updateQuestionById);
router.delete("/quizzes/:question_id", QuizController.deleteQuestionById);
// user routes
router.post("/users", UserController.createUser);
module.exports = router;
All of the /quizzes routes work perfectly fine and i have had no trouble accessing the body. The UserController.createUser method is almost identical to Quizcontroller.createQuestion too so I am very confused.
Here is the user-controller with the createUser function:
const User = require("../models/User");
createUser = async (err, res, req) => {
const body = req.body;
console.log(req.body);
console.log(req.params);
console.log(body);
if (!body) {
return res.status(400).json({
succes: false,
error: "You must provide a body",
});
}
try {
const newUser = new User(body);
console.log(newUser);
if (!newUser) {
return res.status(400).json({ success: false, error: err });
}
const user = await newUser.save();
return res
.status(200)
.json({ success: true, newUser: user, msg: "New user created" });
} catch (err) {
console.error(err.message);
res.status(500).send("Server error");
}
};
module.exports = { createUser };
Here is an image of the postman request I am using to try test this:
[1]: https://i.stack.imgur.com/UHAK5.png
And the user model:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
emailAddress: {
type: String,
required: true,
},
permission: {
type: String,
required: true,
},
auth0Id: {
type: String,
required: true,
},
});
module.exports = mongoose.model("users", UserSchema);
The functional parameter order matters.
its
createUser = async (req, res, next) => // correct format
Not
createUser = async (err, res, req) // wrong format

Categories

Resources