Redux action req.body undefined for express route - node.js

I've been struggling with this feature that's supposed to send redux-form values to my express server and awaiting mongoose model.
The request body once reached the express route doesn't contain the form values that I've sent in the redux-action. The form values are properly console.logged on the client-side (inside the submitInvestment action). Though, once sent to express (using axios) -> console logging the req.body shows undefined
form.js
<form onSubmit={this.props.handleSubmit((values) => { this.props.submitInvestment(values) })}>
export default connect(null, actions)(reduxForm({ form: 'investmentForm' })(InvestmentForm))
actions.js
export const submitInvestment = (values) => async dispatch => {
console.log('before request')
console.log(values)
const res = await axios.post('/api/investments', values);
console.log('after request', res.data)
// dispatch({ type: FETCH_USER, payload: res.data });
};
route.js
module.exports = app => {
app.post('/api/investments', async (req, res) => {
console.log(req.body)
res.sendStatus(200);
});
}
on form submission (console.log browser)
+ server logs an undefined req.body
Additionally; when I attempt to catch the request with the fully built route.js
module.exports = app => {
app.post('/api/investments', async (req, res) => {
const { currency, units, date } = req.body;
const investment = new Investment({
currency,
units,
date,
_user: req.user.id
});
try {
await investment.save();
res.status(200);
} catch (err) {
res.status(422).send(err);
}
});
}
then my server logs are
[0] (node:25154) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot match against 'undefined' or 'null'.
[0] (node:25154) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

The incoming request needs to be handled by the body parser middleware
App.js
app.use(bodyParser.json());

Related

Async/await mvc express problems handling errors with .catch()

I'm trying to handle errors using express middleware, with these lines I have the following errors
user.js controller
app.post('/create', async (req, res, next) => {
const data = await User.create(req.body)
.catch((err) => next(err));
res.status(201).json({ ok: true, ...data });
});
user.js model
UserSchema.statics.create = async function createUser(data) {
delete data.role;
const user = await new this(data).save();
return { token: user.newToken(), user };
};
app.js
app.use((err, req, res, next) => {
res.status(err.code || 400);
res.json({ ok: false, err: err.message });
});
Errors
(node:3304) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
...
(node:3304) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 9)
(node:3304) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
After to proof with try/catch in the user.js controller i don't have any error, but in the express documentation use try/catch is not recommended.
app.post('/create', async (req, res, next) => {
try {
const data = await User.create(req.body)
res.status(201).json({ ok: true, ...data });
} catch (err) {
next(err);
}
});
Any ideas?
You either use await or then/catch:
app.post('/create', async (req, res, next) => {
User.create(req.body)
.then(data => {
res.status(201).json({ ok: true, ...data });
})
.catch((err) => next(err));
});

Express login: UnhandledPromiseRejectionWarning: Unhandled promise rejection

Good day developers im trying to trigger a process of login for users in my app, generating a token for security reasons, but for some situation im receiving this error
(node:11088) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async
function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:11088) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
despite of allowing the user to log, but then the token although is created isn't exposed on the login json i generated for app purposes checked from my postman.
Lets say i do start the process first in my folder of token generator, after install jsonwebtoken package
jsonwebtoken generation folder
const jsonwebToken = require("jsonwebtoken");
const generateToken =async (userId) => {
return new Promise((reject, resolve) => {
const tokenPayload = { userId };
jsonwebToken.sign(
tokenPayload,
process.env.TOKEN_SECRET_WORD,
{
expiresIn: "12h",
},
(error, generatedToken) => {
if (error) {
reject("cant generate token");
} else {
resolve(generatedToken);
}
}
);
});
};
module.exports = { generateToken };
Once the process of generate the token is set , on my controller for the loginUser function , i set this
et User = require("../modelos/UserModel");
const { response } = require("express");
const cryptoPass = require("bcryptjs");
const { generateToken } = require("../jsonwebtoken/jsonWebTokenGenerator");//path to the json generator
const loginUser = async (request, response = response) => {
const { userEmail, userPassword } = request.body;
try {
const userInDb = await User.findOne({ userEmail });
if (!userInDb) {
return response.status(400).json({
ok: false,
message: "Not user Found",
});
}
const passwordValid = await cryptoPass.compareSync(
userPassword,
userInDb.userPassword
);
if (!passwordValid) {
return response.status(400).json({
ok: false,
message: "Error in Password",
});
}
const tokenGenerated = generateToken(userInDb.id);//generating the tooken in the process
//in order to add it to the user logged json
//once the response is ok(200)
response.status(200).json({
ok: true,
message: "User Logged",
tokenGenerated,//no token
});
} catch (error) {
response.status(500).json({
ok: false,
message: "Some error happened in login",
});
}
};
module.exports = {
loginUser,
};
But then despite of loggin the user , the token isn't brought in the response and that error shows up:
Is weird but if i use an await when asigning the user id to the method of generate token , and then i trigger all the process, then the login isn't successful, and console loggin the catch of that error brings me the token in fact:
......
const tokenGenerated =await generateToken(userInDb.id);//adding an await
// console.log(tokenGenerated,"controller token");
// console.log(userInDb);
response.status(200).json({
ok: true,
message: "User Logged",
tokenGenerated,
});
} catch (error) {
console.log(error,"Error");//loggin the error in the catch
response.status(500).json({
ok: false,
message: "Some error happened in login",
});
}
and in postman the not successful login
Would be amazing any help on this . Thanks in advance!!
The signature of the callback in new Promise() within generateToken is wrong
You are using
return new Promise((reject, resolve) => {
...
});
but the correct one is
return new Promise((resolve, reject) => {
...
});
ie, you switched the resolve and reject parameter. Thus when in your method you try to call resolve(generatedToken); you are actually rejecting your promise with an error of the generated token.

Node.js: Cannot read property 'password' of undefined in route

I am trying to implement my first user login authentication with jwt. I have a registration endpoint, where I have populated fake data. Now I want to login with the data I have in database. I am testing via Postman, but I have an error which is
[Object: null prototype] {
email: 'fakeEmail#gmail.com\t',
password: '12345678'
}
(node:14781) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'password' of undefined
at /home/me/coding/project/backend/routes/user.js:38:40
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:14781) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:14781) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
POST /user/login - - ms - -
Assuming it might be because of bodyparser, i have tried both way
//app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser());
but same error.
Here is my login endpoint
router.post("/login",(req, res) => {
const {email, password } = req.body;
console.log(req.body)
pool
.query("SELECT * FROM users WHERE email = $1 AND password = $2 LIMIT 1", [email, password ])
.then(res => {
const data = res.rows[0];
if ( email && password === data.password) {
const token = jwt.sign({ email: req.body.email }, "mySecretKey", {
expiresIn: "30 day",
});
res.send(token);
} else {
res.sendStatus(401);
}
});
});```
You have a problem in res object try loging res in then block. res.rows[0] seems undefined
My problem was, that I have registration endpoint, where I am using Bcrypt, and I had to Verify in Login endpoint. Therefore I was getting errors.
So, here is my corrected Login endpoint
router.post("/login", (req, res) => {
const { email, password } = req.body;
pool
.query("SELECT * FROM users WHERE email = $1 LIMIT 1", [email])
.then((result) => {
const data = result.rows[0];
if (result.rows.length > 0 && email) {
bcrypt.compare(password, data.password, function (err, result) {
if (result) {
const token = jwt.sign({ email: req.body.email }, "mySecretKey", {
expiresIn: "30 days",
});
res.send(token);
} else {
res.sendStatus(401);
}
});
} else {
res.sendStatus(401);
}
});
});
I hope, it will help someone having similar issue

I have an error in my registration routes

During the course of testing if my user's registration route is working fine using postman as a testing machine, it throw an error that I don't know what it means.
I have tried using an async function to catch the error, but it didn't work out
const express = require('express');
const router = express.Router();
// Use to help set a default image for users
const gravatar = require('gravatar');
// Use to encrypt our password from bringing plain text
const bcrypt = require('bcryptjs');
// I add the user model from my model
// So i can be able to check create a new registration
// and also check if email exist
const User = require('../../models/User');
// #route GET api/users/register
// #desc Register user
// #access Public
router.post('/register', (req, res) => {
User.findOne({ email: req.body.email }).then(user => {
if (user) {
errors.email = 'Email already exists';
return res.status(400).json(errors);
} else {
const avatar = gravatar.url(req.body.email, {
s: '200', // Size
r: 'pg', // Rating
d: 'mm' // Default
});
const newUser = new User({
name: req.body.name,
email: req.body.email,
avatar,
password: req.body.password
});
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then(user => res.json(user))
.catch(err => console.log(err));
});
});
}
});
});
module.exports = router;
I want the user input on postman should be able to post the form so I can know if the route is actually working fine. And this is the error I got on my console
(node:14164) UnhandledPromiseRejectionWarning: ReferenceError: errors is not defined
at User.findOne.then.user (the working director/name.js:26:7)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:14164) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:14164) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Normally we should handle the error in a kind of this way:
User.findOne({ email: req.body.email }).then(user => {
// ...
}).catch(error => {
console.log('error', error)
res.json({error: error})
})

Getting an UnhandledPromiseRejectionWarning when posting to a NodeJS backend

Need a little help. Been learning NodeJS. And so far so good. But I am running into an issue when I try to create a new ToDo object that's associated with an authenticated user.
I get the following error
(node:54162) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:54162) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Here is the offending code:
app.post('/todos', authenticate, (req, res) => {
var todo = new Todo({
text: req.body.text,
_creator: req.user._id
});
todo.save().then(() => {
res.send(todo);
}).catch((e) => {
res.status(400).send(e);
});
})
I am not sure what I am missing. I've read in certain places about try catch mismatches. But I am still not sure.
Just for more context, I have also added my authenticate.js
var {User} = require('./../models/user');
//Definining endpoint authentication middleware
var authenticate = (req, res, next) => {
var token = req.header('x-auth');
User.findByToken(token).then((user) => {
if(!user) {
return Promise.reject();
}
req.user = user;
req.token = token;
next();
res.send(user);
}).catch((e) => {
res.status(401).send();
});
};
module.exports = {authenticate};

Resources