POSTMAN API Request of (POST) is not working - node.js

I am new to node.js and facing some errors. I am trying to send a POST request on Postman but it's giving me blank with no data in it. And also I checked if my data is valid or not then I got, the data I am sending is valid. Can anyone suggest me?
This is my index File(index.js):
const express = require("express");
const app = express();
const dotenv = require("dotenv");
const mongoose = require("mongoose");
//Import Routes
const authRoute = require("./routes/auth");
const postRoute = require("./routes/posts");
dotenv.config();
//connect to DB
mongoose.connect(
process.env.DB_CONNECT,
{ useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true },
() => console.log("connected to DB!!")
);
//Middleware
app.use(express.json());
//Route Middlewares
app.use("/api/user", authRoute);
app.use("/api/posts", postRoute);
//PORT NUMBER
const port = process.env.PORT || 8080; // default port to listen
// start the Express server
app.listen(port, () => {
console.log(`server started at http://localhost:${port}`);
});
This is my Auth file(auth.js):
const router = require("express").Router();
const User = require("../model/User");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
const { registerValidation, loginValidation } = require("../validation");
//REGISTER
router.post("/register", async (req, res) => {
console.log("register");
//Lets validate a data before we make a user
const { error } = registerValidation(req.body);
if (error) return res.status(400).send(error.details[0].message);
//Checking if the user is already in the database
const emailExist = await User.findOne({ email: req.body.email });
if (emailExist) return res.status(400).send("Email Already Exists");
//HASH THE PASSWORD
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt);
//Create a New User
const user = new User({
name: req.body.name,
email: req.body.email,
password: hashedPassword,
});
try {
const savedUser = await user.save();
res.send({ user: user._id });
} catch (err) {
res.status(400).send(err);
}
});
//LOGIN
router.post("/login", async (req, res) => {
//Lets validate a data before we make a user
const { error } = loginValidation(req.body);
if (error) return res.status(400).send(error.details[0].message);
//Checking if the email exists in the database
const user = await User.findOne({ email: req.body.email });
if (!user) return res.status(400).send("Email is Not Found");
//Check if password is correct
const validPass = await bcrypt.compare(req.body.password, user.password);
if (!validPass) return res.status(400).send("Invalid Password");
//Create and assign a Token
const token = jwt.sign({ _id: user._id }, process.env.TOKEN_SECRET);
res.header("auth-token", token).send(token);
});
module.exports = router;
As you can see:
I am not able to send data and fetch it with the POST request, DB is connected too.

Try console.log(req.body).
If your req.body is empty then you need to add a package body-parser in middleware(index.js file).
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));

Related

Mongoose: Operation `schema.findOne()` buffering timed out after 10000ms

I have a REST API made with Node.js and I use Mongoose to connect with MongoDB. Whenever I try to interact with the DB using Mongoose, I get the timeout error.
I have made sure that the DB is running and accepts connections from my IP. Using the same connection method in other projects works for some reason.
I am using mobile hotspot connection. Could that be an issue?
server.js
const express = require('express');
const app = express();
const cors = require('cors');
const userRoutes = require('../Backend/routes/userRoutes')
const taskRoutes = require('../Backend/routes/taskRoutes')
const mongoose = require('mongoose');
require('dotenv').config()
mongoose.connect(process.env.DB_CONNECTION);
app.use(cors());
app.use(express.json());
app.use(userRoutes)
app.use(taskRoutes)
app.listen(process.env.PORT || 3000 , () => {
console.log("API is now running.")
});
userRoutes.js
const userController = require('../controllers/userController')
const express = require('express');
const router = express.Router();
router.get('/users/currentUser', userController.getCurrentUserData)
router.get('/users/:userId', userController.getUserData)
router.post('/register', userController.register);
router.post('/login', userController.login);
module.exports = router;
Method in userController that causes the error (the error is caused by no matter which method I call out)
exports.login = async (req, res) => {
if (!req.body.username || !req.body.password) {
return res.status(400).send("Missing one or all required request body fields: username, password");
}
let existingUser;
try {
existingUser = await userSchema.findOne({ username: req.body.username });
} catch(err) {
return res.status(500).send("Internal server error."); //Error comes from here
}
if (!existingUser) {
return res.status(404).send('User not found');
}
const isPasswordCorrect = await bcrypt.compare(req.body.password, existingUser.password);
if (!isPasswordCorrect) {
return res.status(401).send('Invalid credentials');
}
let token;
try {
token = jwt.sign(
{ userId: existingUser._id, username: existingUser.username, tasks: existingUser.tasks},
process.env.SECRET,
{ expiresIn: "1h" }
);
} catch (err) {
console.log(err);
return res.status(500).send("Couldn't create JWT.")
}
return res.status(200).json({ token: token });
}
User model
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const userSchema = new mongoose.Schema({
username:{
type: String,
unique: true
},
password:{
type: String
},
tasks:{
type:[mongoose.Types.ObjectId]
}
})
userSchema.pre('save', async function(next) {
const salt = await bcrypt.genSalt();
this.password = await bcrypt.hash(this.password, salt);
next();
});
module.exports = mongoose.model('user',userSchema);
.env
DB_CONNECTION="mongodb://localhost:27017/test"
SECRET='test'

cannot get api/auth/logowanie problem node.js

When I try to get data from my db I get an information "Cannot GET /api/auth/logowanie". I'm using node.js and mongodb. I've tried to solve it but nothing worked. (the port and url is in 100% correct)
My auth.js file
const router = require('express').Router();
const CryptoJs = require('crypto-js');
const User = require('../models/user');
//REJESTRACJA
router.post('/rejestracja', async (req, res)=>{
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: CryptoJs.AES.encrypt(req.body.password, process.env.PASS_SEC).toString(),
});
try{
const saveduser = await newUser.save();
res.status(201).json(saveduser);
}catch(err){
res.status(500).json(err);
}
});
//LOGOWANIE
router.post('/logowanie', async (req, res) => {
try{
const user = await User.findOne({username: req.body.username});
!user && res.status(401).json("Wrong username or password")
const hashedpassword = CryptoJs.AES.decrypt(user.password, process.env.PASS_SEC);
const password = hashedpassword.toString(CryptoJs.enc.Utf8);
password !== req.body.password &&
res.status(401).json("Wrong username or password")
res.status(200).json(user);
}catch(err){ res.status(500).json(err); }
})
module.exports = router
My index.js file
const express = require('express');
const app = express();
const dotenv = require('dotenv');
dotenv.config();
const userRoute = require("./routes/user");
const authRoute = require("./routes/auth");
const mongoose = require('mongoose');
const { CLIENT_RENEG_LIMIT } = require('tls');
const { application } = require('express');
mongoose
.connect(process.env.MONGO_URL)
.then(() => console.log('Connected to Mongoose server'))
.catch((err) => {
console.log(err);
});
app.use(express.json());
app.use('/api/users', userRoute);
app.use('/api/auth', authRoute);
app.listen(process.env.PORT || 5300, ()=>{
console.log('Listening on port 5300');
});
And screenshot from Postman
Your endpoint in the auth.js file is a POST request. And you are sending a GET request from Postman.

Node.js Canno't GET or POST users from route

I am doing backend login and register project with Nodejs and Express but somehow I cannot login or register anymore or even fetch data from my usersRoute and I don't know why. I am lost..
My index.ts file:
import express from "express";
const https = require("https");
import cors from "cors";
import mongoose from "mongoose";
const app = express();
//import Routes
const usersRoute = require("./routes/users");
//Middleware
app.use(cors());
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
//Route middlewares
app.use("api/users", usersRoute);
//connect to db
mongoose
.connect("mongodb://localhost:27017/containerlab")
.then(() => {
console.log("connected to database");
})
.catch(() => {
console.log("connection failed!");
});
const PORT = 5000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
My users.ts file
import express from "express";
const router = express.Router();
const User = require("../models/User");
const {
registerValidation,
loginValidation,
} = require("../middleware/validation");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const secretKey = "f43g34gergeerg";
const verifyToken = require("../middleware/verifyToken");
//REGISTER user
router.post("/register", async (req, res) => {
//VALIDATE DATA from Joi, before register
const { error } = registerValidation(req.body);
if (error) return res.status(400).send(error.details[0].message);
//check if user is alredy in database
const emailExist = await User.findOne({ email: req.body.email });
if (emailExist) return res.status(400).send("Email already exists");
//encrypt password z bcryptjs modulom
const salt = await bcrypt.genSalt(10);
const hashPassword = await bcrypt.hash(req.body.password, salt);
//create new user
const user = new User({
email: req.body.email,
password: hashPassword,
});
try {
//save new user
const savedUser = await user.save();
//res.json(savedUser);
res.json({ user: user._id });
} catch (err) {
res.json({ message: err });
}
});
//LOGIN
router.post("/login", async (req, res) => {
//VALIDATE DATA from Joi, before register
const { error } = loginValidation(req.body);
if (error) return res.status(400).send(error.details[0].message);
//check if email exists.. če NE obstaja mail dobiš da ne ustreza
const user = await User.findOne({ email: req.body.email });
if (!user) return res.status(400).send("Email doesn't exist");
const validPass = await bcrypt.compare(req.body.password, user.password);
if (!validPass) return res.status(400).send("Invalid password");
//create and send a json web token
const token = jwt.sign({ _id: user._id }, secretKey, { expiresIn: "1h" });
res.header("auth-token", token).send(token);
res.send("Logged in!");
});
//get users
router.get("/", async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (err) {
res.json({ message: err });
}
});
module.exports = router;
And my verifyToken.ts middleware
const jwt = require("jsonwebtoken");
const secretKey = "f43g34gergeerg";
module.exports = (req: any, res: any, next: any) => {
const token = req.header("auth-token");
if (!token) return res.status(401).send("Access denied");
try {
const verified = jwt.verify(token, secretKey);
req.user = verified;
next();
} catch (err) {
res.status(400).send("Invalid token");
}
};
Somehow I can't fetch ANY data from users.ts (from usersRoute). Thank you for your help

Node/Express cannot get url "Cannot GET /api/auth/register"

I am trying to create a register page. when I route its shows Cannot GET /api/auth/register same thing happened when I route login and others too. i use postman to throw data it's shown 5000 internet server error.
how to solve route problem for register
// tested REGISTER i used it to test this code is runing or not in tutorial this code was runnign and show in register path is "ok"
// tested REGISTER
const express = require("express");
const router = express.Router();
const User = require("../models/User");
router.get("/register", async (req, res) => {
//create new user
const user = await new User({
username:"admin",
email:"admin#gmail.com",
password: "123456"
});
//save user and respond
await user.save();
res.send("Hello")
});
module.exports = router;
index.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const helmet = require("helmet");
const morgan = require("morgan");
const userRoute = require("./routes/users");
const authRoute = require("./routes/auth");
const postRoute = require("./routes/posts");
dotenv.config();
mongoose.connect(
process.env.MONGO_URL,
{ useNewUrlParser: true,
useUnifiedTopology: true
},
() => {
console.log("Connected to MongoDB");
}
);
//middleware
app.use(express.json());
app.use(helmet());
app.use(morgan("common"));
app.use("/api/auth", authRoute);
app.use("/api/users", userRoute);
app.use("/api/posts", postRoute);
app.listen(8000, () => {
console.log("Backend server is running!");
});
auth.js here the login and register file
const express = require("express");
const router = express.Router();
const User = require("../models/User");
const bcrypt = require("bcrypt");
//REGISTER
router.post("/register", async (req, res) => {
try {
//generate new password
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password,salt);
//create new user
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: hashedPassword,
});
//save user and respond
const user = await newUser.save();
res.status(200).json(user);
} catch (err) {
res.status(500).json(err)
}
});
//LOGIN
router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ email: req.body.email });
// make sure user is not empty {} or [];
if (!user) res.status(404).json("user not found");
const validPassword = await bcrypt.compare(req.body.password,
user.password)
// make sure password is not empty {} or [];
if(!validPassword) res.status(400).json("wrong password");
res.status(200).json(user)
} catch (err) {
res.status(500).json(err)
}
});
module.exports = router;

User.find() returns empty response in mongodb express

I'm working with nextjs and express .I'm implementing simple signin form.I'm sending user credential and using find() ,checking whether user exist or not.but find() returns empty response.
In terminal find() returns array of that record.
model
const mongoose = require('mongoose')
const schema = mongoose.Schema
const user = new schema({
username: { type: String} ,
password: { type: String},
role: { type: String},
})
module.exports = mongoose.model('user', user);
router.js
const express = require('express')
const router = express.Router()
const user = require('../models/user');
router.post('/user/signin', (req, res) => {
user.find({
username: req.body.username, password: req.body.password
}, (err, user) => {
console.log(user);
if (err) {
result.status(404).send({ error: 'There is some error' });
} else if (user.length == 1) {
var token = 'kkl';//token
res.send({ token });
} else {
console.log(err);
res.send('Incorrect Email and Password');
}
});
})
module.exports = router;
this.is my index.js
const express = require('express')
const next = require('next')
const bodyParser = require('body-parser')
const PORT = process.env.PORT || 4000
const dev = process.env.NODE_DEV !== 'production' //true false
const nextApp = next({ dev })
const handle = nextApp.getRequestHandler() //part of next config
const mongoose = require('mongoose')
const router = express.Router();
nextApp.prepare().then(() => {
const app = express();
const db = mongoose.connect('mongodb://localhost:27017/knowledgeBase')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/knowledgeBase', require('./routes/router'));
app.get('*', (req, res) => {
return handle(req, res) // for all the react stuff
})
app.listen(PORT, err => {
if (err) {
console.log(err);
throw err;
}
console.log(`ready at http://localhost:${PORT}`)
})
})
please help
What response you get when you try this?
According to the response I will edit response.
router.post("/user/signin", async (req, res) => {
if (!req.body.username) return res.status(400).send("username cannot be null");
if (!req.body.password) return res.status(400).send("Password cannot be null");
const user = await User.findOne({ username: req.body.username});
if (!user) return res.status(400).send("User not found");
if (req.body.password!== user.password)
return res.status(400).send("Invalid password.");
res.send("logined");
});

Resources