// finding users
find: function (req, res, next) {
var userId = req.body.userId;
var userSchema = db.UserModel;
try {
db.sequelize.sync().then(function (params) {
userSchema.findAll({where:{userId:userId}}).then(function (user) {
return res.json({
success:true,
userData:user.get({
plain:true
})
});
});
});
} catch (ex) {
res.json({
success: false,
exception: ex
});
return;
}
}
I was writting simple crud api for my project.
while executing above mentioned code I am getting error on my console as:
Executing (default): SELECT userId, firstname, lastname, email, createdAt, updatedAt FROM Users AS User WHERE User.userId = '1';
Unhandled rejection TypeError: Cannot read property 'get' of undefined
at D:\tecsol\mtv\api\controllers\UserController.js:52:27
at processImmediate [as _immediateCallback] (timers.js:367:17)
user is an array - use findOne or user[0]
Related
I'm trying to do a sample register without JWT using MVC in nodejs, express and mysql so when I run my code and I have an error :
TypeError: Cannot read properties of undefined (reading 'firstName') at exports.register
here is my code :
AuthController
const AuthModel = require('../models/Auth')
// Create and Save a new User
exports.register = (req, res) => {
// Validate request
if (!req.body) {
res.status(400).send({
message: "Content can not be empty!"
});
}
// Create user
const user = new AuthModel({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: req.body.password
});
// Save user in the database
AuthModel.createUser(user, (err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while registring."
});
else res.send(data);
});
};
AuthModel
const AuthModel = function(table){
this.firstName = table.firstName;
this.lastName = table.lastName;
this.email = table.email;
this.password = table.password;
}
AuthModel.createUser = ( newUser, result ) =>{
db.query("INSERT INTO users SET ?", newUser, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
console.log("User are registed: ", { id: res.insertId, ...newUser });
result(null, { id: res.insertId, ...newUser });
});
};
It seems to me as if the req.body is undefined. I think you might need something like body-parser, which has been added into the core of Express starting with version 4.
Try adding this middleware to your entrypoint: app.use(express.json());
See more here: http://expressjs.com/en/api.html#express.json
In your exports.register, you .send() if the body is undefined. That doesn't mean the rest of the code won't be executed.
Replace:
res.status(400).send({
message: "Content can not be empty!"
});
by
return res.status(400).send({
message: "Content can not be empty!"
});
I am using postman with nodejs and MySQL.
Middleware
const notFound = (req, res, next) => {
const error = new Error(`Not Found -${req.originalUrl}`);
res.status(404);
next(error);
};
const errorHandler = (err, req, res, next) => {
const statusCode = res.statusCode === 200 ? 500 : res.statusCode;
res.status(statusCode);
res.json({
message: err.message,
stack: process.env.NODE_ENV === "production" ? null : err.stack,
});
};
export { notFound, errorHandler };
here I am trying to use notFound and errorHandler for the authUser
const authUser = asyncHandler(async (req, res) => {
const { email, password } = req.body;
let sql =
"select #uid :=`user_id`, first_name, last_name, email from dasa_user as var, (SELECT #uid := NULL) init_var where email=?;select #finaluid:= `user_id` from user_type, (SELECT #finaluid := NULL) init_var where user_id =#uid AND type='customer';select customer_id, password from customer where user_id =#finaluid;";
db.query(sql, [email], (err, result) => {
if (err) throw err;
if (result) {
if (result[2][0] == null) {
res.status(401);
throw new Error("user not Found");
} else {
if (MatchPassword(password, result[2]["0"]["password"])) {
res.json({
first_name: result[0][0]["first_name"],
last_name: result[0][0]["last_name"],
email: result[0][0]["email"],
userId: result[1]["0"]["#finaluid:= `user_id`"],
customerId: result[2]["0"]["customer_id"],
password: result[2]["0"]["password"],
token: generateToken(result[0][0]["email"]),
});
} else {
res.status(401);
throw new Error("Invalid email or password");
}
}
} else {
res.status(401);
throw new Error("Invalid email or password");
}
});
});
Now for this particular controller, I am accessing api/users/signin which is valid. But When I use something like api/users/signin/ksds. It does use notFound middleware and gives me error in postman. But in body If I use incorrect password, it should show error in postman console. But what it does it gives me error in vscode console. like this,
And I have to refresh the server everytime.
In order to access the notFoundanderrorHandler, I am using app.use` in server.js like this,
app.use(notFound);
app.use(errorHandler);
How can I solve this? So, that this will help me in showing error in the frontend too.
This errors comes in when you get empty results. You should first check the length of the results then use properties or index on it.
const authUser = asyncHandler(async (req, res) => {
const { email, password } = req.body;
let sql =
"select #uid :=`user_id`, first_name, last_name, email from dasa_user as var, (SELECT #uid := NULL) init_var where email=?;select #finaluid:= `user_id` from user_type, (SELECT #finaluid := NULL) init_var where user_id =#uid AND type='customer';select customer_id, password from customer where user_id =#finaluid;";
db.query(sql, [email], (err, result) => {
try {
if (err) throw err;
if (result.length > 0) {
if (result[2][0] == null) {
res.status(401);
throw new Error("user not Found");
} else {
if (MatchPassword(password, result[2]["0"]["password"])) {
res.json({
first_name: result[0][0]["first_name"],
last_name: result[0][0]["last_name"],
email: result[0][0]["email"],
userId: result[1]["0"]["#finaluid:= `user_id`"],
customerId: result[2]["0"]["customer_id"],
password: result[2]["0"]["password"],
token: generateToken(result[0][0]["email"]),
});
} else {
res.status(401); // this else is calling up for (If you use incorrect password)
throw new Error("Invalid email or password");
}
}
} else {
res.status(401).send({message: 'Results not found'}); // change this to send error message to the frontend, you can really customise it based on your needs.
// throw new Error("Results not found"); // Now this error is thrown because you don't have results
}
} catch (error) {
console.error(e);
}
});
});
But When I use something like api/users/signin/ksds. It does use
notFound middleware and gives me error in postman.
Because you are creating a custom error and sending it to node default error handler which does the work for you and postman receives the error message.
But in body If I use incorrect password, it should show error in
postman console. But what it does it gives me error in vscode console
However, in this case your are throwing an error and it is doing its job and you see that error in the console. If you don't want this behaviour follow the same flow as used above.
Check for more details: How to handle errors in Node.js?
First of all, this is the repo website: https://github.com/TheFJS14/ck-app (you can see all code related to)
I am developing a NodeJS RESTful API with MySQL but, when I am trying to post a new User json, it report an error:
ReferenceError: User is not defined
at exports.create (C:\...\app\controllers\user.controller.js:10:18)
This is my file:
exports.create = (req, res) => {
if (!req.body) {
res.status(400).send({
message: "Content can not be empty!"
});
}
vvvvvvvvv
const user = new User({
nameUser: req.body.nameUser,
emailUser: req.body.emailUser
});
User.create(user, (err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while creating the user."
});
else res.send(data);
});
};
I have other code references:
const UserRole = require("../models/userRole.model.js");
exports.create = (req, res) => {
if (!req.body) {
res.status(400).send({
message: "Content can not be empty!"
});
}
const userRole = new UserRole({
nameUserRole: req.body.nameUserRole,
descriptionUserRole: req.body.descriptionUserRole
});
UserRole.create(userRole, (err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while creating the user role."
});
else res.send(data);
});
};
When I move my mouse over my User model, I get this message:
https://i.stack.imgur.com/1wjwf.png
But, when I see other codes, it looks different with my mouse over them: https://i.stack.imgur.com/bqsOR.png
I probably need to change my variable name, but I prefer not.
Thanks!
I have checked your code in github, in user.controller.js you have added this line:
const UserRole = require("../models/user.model.js");
you have to change it to
const User = require("../models/user.model.js");
That's why it throws and Error that User is not defined
How to handle Delete Query When id not available in App.delete method not giving error .in both case show success. if id not available then it should output id not available to delete task .
same case for get by id method . if id is available it working right . if id not available it did not show error
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mysql = require('mysql');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// connection configurations
const mc = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: '1234'
});
// connect to database
mc.connect();
// default route
app.get('/', function (req, res) {
return res.send({ error: true, message: 'hello' })
});
// Retrieve all todos
app.get('/todos', function (req, res) {
mc.query('SELECT * FROM tasks', function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Todos list.' });
});
});
// Search for todos with ‘bug’ in their name
app.get('/todos/search/:keyword', function (req, res) {
let keyword = req.params.keyword;
mc.query("SELECT * FROM tasks WHERE task LIKE ? ", ['%' + keyword + '%'], function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Todos search list.' });
});
});
// Retrieve todo with id
app.get('/todo/:id', function (req, res) {
let task_id = req.params.id;
mc.query('SELECT * FROM tasks where id=?', task_id, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results[0], message: 'Todos list.' });
});
});
// Add a new todo
app.post('/todo', function (req, res) {
let task = req.body.task;
if (!task) {
return res.status(400).send({ error:true, message: 'Please provide task' });
}
mc.query("INSERT INTO tasks SET ? ", { task: task }, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'New task has been created successfully.' });
});
});
// Update todo with id
app.put('/todo', function (req, res) {
let task_id = req.body.task_id;
let task = req.body.task;
if (!task_id || !task) {
return res.status(400).send({ error: task, message: 'Please provide task and task_id' });
}
mc.query("UPDATE tasks SET task = ? WHERE id = ?", [task, task_id], function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Task has been updated successfully.' });
});
});
// Delete todo
app.delete('/todo/:id', function (req, res) {
let task_id = req.params.id;
if (!task_id) {
return res.status(400).send({ error: true, message: 'Please provide text_id' });
}
mc.query('DELETE FROM tasks WHERE id = ?', task_id, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'text has been Deleted successfully.' });
});
});
// all other requests redirect to 404
app.all("*", function (req, res) {
return res.status(404).send('page not found')
});
// port must be set to 8080 because incoming http requests are routed from port 80 to port 8080
app.listen(8080, function () {
console.log('Node app is running on port 8080');
});
// allows "grunt dev" to create a development server with livereload
//module.exports = app;
You have to define the param as optional.
Express uses path-to-regexp for matching the route paths; see the
path-to-regexp documentation for all the possibilities in defining
route paths. Express Route Tester is a handy tool for testing basic
Express routes, although it does not support pattern matching.
https://expressjs.com/en/guide/routing.html
Works for /todo and /todo/{id},
route - /todo/:id*?
// Delete todo
app.delete('/todo/:id*?', function (req, res) {
});
I am working on an Express App with MongoDB and trying to utilize FeathersJS for all my services. Here I'm running a test try to get an error message from the server to the client, but I have an issue with the response from the error handler. My req headers have the correct application/json stuff, so I assumed the Error Handler should send valid json back.
I know I'm not using the next callback in my function, but when I try to do that it gives the same error, so I'm thinking it has to do with the Error Handler. Any direction here would be greatly appreciated!
The first error log is on the server, which is correct.
Bucket Services
error >>>>> Bucket validation failed
Possibly Unhandled Rejection: Bucket validation failed, Promise { <rejected> 'Bucket validation failed' }
>>>>>> Error: Unexpected token < in JSON at position 0
at convert (/Users/jaruesink/Documents/Projects/Buckets/node_modules/feathers-rest/node_modules/feathers-errors/lib/index.js:365:79)
at toError (/Users/jaruesink/Documents/Projects/Buckets/node_modules/feathers-rest/lib/client/base.js:24:37)
at process._tickCallback (internal/process/next_tick.js:103:7)
my create function within the BucketService class:
create({
amount,
isFund = false,
name,
type,
userID: owner
}, params, next) {
const new_bucket = new Bucket({ name, amount, type, isFund, owner });
return new_bucket.save((error) => {
console.log('error >>>>>', error.message);
if (error) { return Promise.reject(error.message); }
return Promise.resolve(new_bucket);
});
}
my router file:
const feathers = require('feathers');
const errorHandler = require('feathers-errors/handler');
const rest = require('feathers-rest');
const router = feathers();
const LoginService = require('../services/login_service');
const UserService = require('../services/user_service');
const BucketService = require('../services/bucket_service');
// Enable REST services
router.configure(rest());
router.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
router.use('/login', new LoginService());
router.use('/user', new UserService());
router.use('/bucket', new BucketService());
// Set up error handling
router.use(errorHandler());
module.exports = router;
I figured it out, the key was to correctly pass through a callback (next) function as the third parameter to handle errors. FeathersJS handles the Promise Rejections for you on errors. Then in my test I needed to convert the Feathers-Error to JSON before I could get the message.
I changed my test to:
it('can validate an incorrect bucket', (done) => {
const invalid_bucket = {
name: 'Invalid Bucket',
};
bucket_service.create(invalid_bucket, {}, (error) => {
error = error.toJSON();
assert(error.message.length > 0);
done();
});
});
and my create function to:
create({
amount,
isFund = false,
name,
type,
userID: owner
}, params, next) {
const new_bucket = new Bucket({ name, amount, type, isFund, owner });
return new_bucket.save()
.then(created_bucket => Promise.resolve(created_bucket))
.catch(next);
}