My Express API exposes a POST endpoint to create a user, and i need to validate data before inserting it into database, i have two methods in mind:
Method 1: Include the model's validation in the controller and repeat it for every model:
// controllers/users.js
exports.createUser = async function (req, res) {
const { username, email, password } = req.body;
/* validation logic */
/* interact with db */
Method 2: Move the validation logic to dedicated middleware:
// middleware/validators.js
exports.validateArticle = function (req, res, next) {};
exports.validateComment = function (req, res, next) {};
exports.validateUser = function (req, res, next) {
const { username, email, password } = req.body;
/* validation logic */
if (!isValid) {
return res.statusCode(400);
}
next();
};
// routes/users.js
const { validateUser } = require('../middlewares/validators');
router.route('/').post(validateUser, createUser);
my concern with method 2 is that the logic for one endpoint method would be scattered among many files, but which one of these methods follow best practices ?
I can suggest you to use a ready-made middlewares express-validator, and setup like that:
// src/validation/validation.js
const { validationResult } = require('express-validator');
const validate = (schemas) => {
return async (req, res, next) => {
await Promise.all(schemas.map((schema) => schema.run(req)));
const result = validationResult(req);
if (result.isEmpty()) {
return next();
}
const errors = result.array();
return res.send({
message: 'Validation error',
errors: errors,
})
};
}
module.exports = {
validate
}
this is a function that you can call like middleware in your router, then a file with validation rules.
// src/validation/validationSchemas.js
const { body } = require('express-validator');
const addUserSchema = [
body('username').isLength({ min: 4, max: 16 }).withMessage('Username must be at least 4 and no more than 16 characters'),
body('email').isEmail().withMessage('Incorrect email')
];
module.exports = { addUserSchema }
and in your router:
const { validate } = require('../validation/validation');
const { registrationSchema, loginSchema } = require('../validation/validationSchemas');
router.post('/registration', validate(registrationSchema), userController.registration);
The issue is one of scale. If there are a lot of different routes in a controller, or if you just have multiple controllers, it can be difficult to keep things clean and easy to understand. The controller shouldn't have much more than what is necessary to show how incoming requests are being routed and returned. Everything else that isn't trivial should be passed to a middleware service. Therefore, the second option tends to work out better if you want room to grow.
Additionally, by putting all your validation logic together you can easily reuse code where applicable.
Option 1 can work out if this is very static and you have no expectations that new routes or controllers will be added.
Introduction
So, I'm using the MERN stack (with Heroku + Netlify), and I'm having some really strange consistency problems with how the DELETE request is being handled. I've tried countless solutions in the last
three days trying to get this to work and none of them have worked. A lot of these solutions have
come from stack overflow, so if you want to direct me to another post, the chance is that I've already seen it. I've scoured every part of the web and making this post is my last resort.
The Problem
So, when I make a delete request, I'm getting the per-usual OPTIONS request since I'm sending a token in a custom header of the request ('x-auth-token'). The OPTIONS request always resolves with a 204, meaning that everything should be alright. However, afterward, there is no DELETE request like there should be. This, in essence, is my problem. I've checked my Heroku logs, and all I can see is the OPTIONS request, and nothing else.
Inconsistencies?
So this is where I've been very confused. The thing is, that sometimes it DOES work. And other routes I use in my API (like login, and creating a new post) work, even though I'm using the same middleware.
Every time it works, I get the OPTIONS request and then the DELETE request (with a 200 status) like I would expect to happen.
If you want an example of a re-creatable scenario:
I create X number posts after logging in and getting a valid token, then I can see those posts rendering in the posts listing on my home page. I then navigate one of the posts and delete it by clicking and then a confirmation button. I automatically get redirected to the next post in the list. I repeat this till I get to the last post. I delete that post, and since there are no more posts left, I get redirected to the posts listing which is... not empty! The last post I tried deleting is still there.
Keep in mind, that the DELETE requests all get sent in exactly the same way, so I'm pretty sure this isn't a front-end issue, so no need to poke around in the code there. I've logged everything and debugged, and it's 100% consistent with what I would expect.
(The create post doesn't redirect, while the delete post does? I don't see how this would effect anythign as the DELETE request gets sent as per usual... Though maybe a solution lies within this fact.)
Solutions I've tried
Cors
First off, you might already be rushing to your keyboard to tell me that this is a CORS issue. I thought the same thing yesterday, but I'm not so sure now. I've tried messing with all the config settings possible in CORS to get this to work. Since my two websites are on different domains, then CORS verifies the requests. I've already added my front-end website to a whitelist, and all other requests are going through properly, so no problem there. I've tried adding an allowHeaders option in the config, but it didn't do anything more than the default setting. I've also added 'OPTIONS' to the allowed methods in the config, still nothing. I'm also using app.use(cors({config})). I'll include some code later to see some more of this in detail.
Debugging
I've basically tested things out by inserting console.logs everywhere and discovered that neither the middleware, the options route (I tried making an options route with same route url), or the original post route get executed when the OPTIONS request doesn't result in a DELETE request.
Static Server
This is maybe where some of my inexperience shows (this is my first Web project). I saw some solutions telling that a static server is needed. So I tried setting up a static server, but I didn't see any results. So I'm not too sure what this accomplished.
Async and Await
I was just trying things at this point, so I made all my routes async to see if it would do anything. It didn't.
Others
I've also messed around with environment variables and dotenv, and other stuff I can't remember. I think everything here should already be sufficient information understand the situation.
Code
index.js
const express = require('express');
require("dotenv").config({ path: "variables.env" });
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const routes = require("./routes/router");
const cors = require("cors");
const morgan = require('morgan')
const app = express();
const whitelist = [
process.env.ORIGIN
];
app.use(
cors({
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
console.log(origin);
callback(new Error("Not allowed by CORS"));
}
}, //frontend server localhost:3000
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
credentials: true, // enable set cookie
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan('dev'));
mongoose.connect(process.env.MONGODB_URL, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('connected to db');
});
const userSchema = mongoose.Schema({
name: String,
password: String
});
// Routes
// TODO: make seperate routers/routes
app.use("/", routes);
// Serve static assets if in production
if (process.env.NODE_ENV === 'production') {
// Set static folder
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
// TODO: set up custom port in future
app.listen(process.env.PORT, () => console.log(`Server listening at http://localhost:${process.env.PORT}`));
// Callback functions?
router.js
const express = require('express');
const router = express.Router();
const Post = require('../models/Post');
const User = require('../models/User');
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const auth = require('../middleware/auth');
const adminAuth = require('../middleware/adminAuth');
const cors = require("cors");
require("dotenv").config({ path: "variables.env" });
// import 'moment'
// second onwards are handlers => triggers like the post body then next() to go to the next handler
router.post('/api/add_post', adminAuth, async (req, res, next) => {
try{
newPost = new Post({
title: req.body.title,
body: req.body.body,
author: req.body.author,
created: req.body.created,
});
const savedPost = await newPost.save();
if (!savedUser) throw Error('Something went wrong saving the post');
res.send(savedPost);
} catch (e) {
res.status(400).json({ msg: e.message });
}
});
router.delete('/api/delete_post/:id', adminAuth, async (req, res, next) => {
// timeout?
// console.log(req.body);
try{
const id = req.params.id;
if(!id) throw Error('Invalid ID');
const post = await Post.findById(id);
if (!post) throw Error('Post doesn\'t exist');
const removed = await post.remove();
if(!removed) throw Error('Problem with deleting the post');
res.status(200).json({ success: true });
} catch(e) {
console.log("Error: ", e.message);
res.status(400).json({ msg: e.message, success: false });
}
});
// TODO : UPDATE for async soon
router.post('/api/update_post', adminAuth, async (req, res, next) => {
const id = req.body._id;
test_post_data = {
title: req.body.title,
body: req.body.body,
author: req.body.author,
modified: req.body.modified,
};
console.log(test_post_data, id);
Post.updateOne({ _id: id }, test_post_data, (err) => {
if(err) return next(err);
return res.status(200);
});
});
router.get('/api/get_posts', async (req, res, next) => {
try{
const posts = await Post.find();
if(!posts) throw Error('Error with fetching the posts')
res.send(posts.reverse());
} catch (e) {
res.status(400).json({ msg: e.message });
}
});
router.get('/api/get_chapter/:id', async (req, res, next) => {
try{
const id = req.params.id;
const post = await Post.findOne({_id: id})
if(!post) throw Error('No post was found')
res.send(post);
} catch(e) {
res.status(400).json({ msg: e.message })
}
});
// User routes
// TODO : make in seperate file
router.post('/api/user/register', async (req, res) => {
const { name, email, password } = req.body;
// Simple validation
if (!name || !email || !password) {
return res.status(400).json({ msg: 'Please enter all fields' });
}
try {
const user = await User.findOne({ email });
if (user) throw Error('User already exists');
const salt = await bcrypt.genSalt(10);
if (!salt) throw Error('Something went wrong with bcrypt');
const hash = await bcrypt.hash(password, salt);
if (!hash) throw Error('Something went wrong hashing the password');
const newUser = new User({
name,
email,
password: hash,
admin: false
});
const savedUser = await newUser.save();
if (!savedUser) throw Error('Something went wrong saving the user');
// TODO : check up on expires stuff : 3600 = 1 hr
const token = jwt.sign({ id: savedUser._id, admin: savedUser.admin }, process.env.JWT_SECRET, {
expiresIn: 3600
});
res.status(200).json({
token,
user: {
id: savedUser.id,
name: savedUser.name,
email: savedUser.email,
admin: savedUser.admin
}
});
} catch (e) {
res.status(400).json({ error: e.message });
}
});
router.post('/api/user/login', async (req, res) => {
const { name, password } = req.body;
// Simple validation
if (!name || !password) {
return res.status(400).json({ msg: 'Please enter all fields' });
}
try {
// Check for existing user
const user = await User.findOne({ name });
if (!user) throw Error('User Does not exist');
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) throw Error('Invalid credentials');
const token = jwt.sign({ id: user._id, admin: user.admin }, process.env.JWT_SECRET, { expiresIn: 3600 });
if (!token) throw Error('Couldnt sign the token');
res.status(200).json({
token,
user: {
id: user._id,
name: user.name,
email: user.email,
admin: user.admin
}
});
} catch (e) {
res.status(400).json({ msg: e.message });
}
});
module.exports = router;
adminAuth.js
const jwt = require('jsonwebtoken')
require("dotenv").config({ path: "variables.env" });
module.exports = (req, res, next) => {
console.log(req.header('x-auth-token'));
const token = req.header('x-auth-token');
// Check for token
if (!token)
return res.status(401).json({ msg: 'No token, authorizaton denied' });
try {
// Verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET);
console.log('decoded:', decoded);
if(!decoded.admin)
return res.status(401).json({ msg: 'Not an admin, authorization denied' });
// Add user from payload
// console.log('decoded:', decoded);
req.user = decoded;
next();
} catch (e) {
res.status(400).json({ msg: 'Token is not valid' });
}
};
Link for request examples, and Heroku log since Stackoverflow says it's spam:
https://gist.github.com/macklinhrw/b2fec97642882ba406c49cce3e195c39
Edit
I pasted the Chrome request and response headers into the gist at the bottom, but there was no response data to go along with either.
I've debugged a little using this to check the difference and I discovered that with delete action that ends up working, the red (canceled) request has headers, while the non-working is completely empty (filled with 'provisional headers' if that means anything).
I couldn't copy-paste the request headers into the gist for the working red (canceled) one. But, I pasted everything that I thought could possibly be useful from chrome, hopefully it helps.
Also, I didn't see any DELETE requests when I was using the Chrome network tool, and I was seeing them on the other tool. Not sure if it matters, probably just a config option somewhere.
So, I haven't found an exact answer, but I've found a workaround.
As it turns out, it might have something to do with axios, and I've been searching for the wrong things in the last 3 days.
This thread helped me: https://github.com/axios/axios/issues/1428
I've added an e.preventDefault() to the onClick method I use for the delete button.
This fixed the problem, but doesn't redirect (I use href={link}), so I'm going to add a conditional render for react-router to redirect the page. I don't know of a better method so maybe give me some ideas. I'll edit if I have further troubles.
Suppose each users has huge amount of data that no need to store those in single table. I want to store each user's data in separate database for faster query.
I want when any user logging in loopback, change datasets based on users connection strings that stored in User model.
I read all of loopback docs and try so many practice to do this but i can't implement this.
I try this in server/server.js:
app.use(loopback.context());
app.use(loopback.token());
app.use(function (req, res, next) {
if (!req.accessToken) {
return next();
}
app.models.User.findById(req.accessToken.userId, function(err, user) {
if (err) {
return next(err);
}
if (!user) {
return next(new Error('No user with this access token was found.'));
}
console.log('server.js');
var loopbackContext = loopback.getCurrentContext();
if (loopbackContext) {
loopbackContext.set('currentUser', user);
}
var DataSource = require('loopback-datasource-juggler').DataSource;
var ds = new DataSource('memory');
app.datasources.db= ds;// <----- IT DOES'NT WORKING
next();
});
});
but IT DOES'NT WORKING (marked in code).
Any idea to solve this issue?
You can use attachTo() function to attach a datasource based on conditions.
app.use(loopback.context());
app.use(loopback.token());
app.use(function (req, res, next) {
if (!req.accessToken) {
return next();
}
app.models.User.findById(req.accessToken.userId, function(err, user) {
if (err) {
return next(err);
}
if (!user) {
return next(new Error('No user with this access token was found.'));
}
//console.log('server.js');
var loopbackContext = loopback.getCurrentContext();
if (loopbackContext) {
loopbackContext.set('currentUser', user);
}
// This way you can attach memory datasource to model.
// This only covers models defined using app.model();
var models = app.models();
models.foreach(function(model) {
model.attachTo(app.dataSources.memory);
});
next();
});
});
Also use defined datasource, memory in datasource.json.
{
"memory": {
"name": "memory",
"connector": "memory"
}
}
Please refer this too: app.models()
I am new with node.js, mongoDB and jade.
To redirect to userlist page I have following route in /routes/index.js
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
This route redirects me to userlist page. There I display a list of all users. Here I have a link on each record to view details:
following is my userlist.jade
extends layout
block content
h1.
User List
ul
each user, i in userlist
li
a(href="/viewuser/id/#{user._id}")=user.username
This:
a(href="/viewuser/id/#{user._id}")=user.username
Gives me:
Dhara
Now I don't know what route should be there for view details on click of the link and how to get selected record data for view screen.
I use a clear and distributed stack MEAN.js, with a yeoman constructor that will help you to build secure and good-practice programming applications.
This is the way I get a concrete user data. It´s a little more spread than your code but it´s clear.
Hope it helps!
routes.js
app.use('/api/users', require('./api/user'));
api/user/index.js
var controller = require('./user.controller');
router.get('users/:id', controller.show);
user.controller.js:
// Get a single user
exports.show = function(req, res) {
User.findById(req.params.id, function (err, user) {
if(err) { return handleError(res, err); }
if(!user) { return res.send(404); }
return res.json(user);
});
};
then I´ll call for a user with an url like users/xxxxxx where xxxx is the user id. Then if you want to do it like /viewuser/id/xxxxxx you will need to change the route like this:
api/user/index.js
var controller = require('./user.controller');
router.get('viewuser/id/:id', controller.show);
user.controller.js:
// Get a single user
exports.show = function(req, res) {
User.findById(req.params.id, function (err, user) {
if(err) { return handleError(res, err); }
if(!user) { return res.send(404); }
return res.json(user);
});
};
maybe you need to specify the view in your app server file
app.get('/userlist', function(req, res){
res.render('userlist', {
title: 'Your_Title'
});
});
I hope to be helpful!
I am currently working on boiler plate code of mean.io and implementing passwordresetemail to it. When ever user asks for password reset with email as parameter, I create a salt(resetid) and send him an email having that salt as reset link.
I have user's email in the req but want to append other information of the user(user._id) before it enters into actual createemail controller function. I want following function(userbyemail) to be run before it goes into createResetPasswordEmailLink
/**
* Find user by email
*/
exports.userByEmail = function(req, res, next, email) {
User
.findOne({
email: email
})
.exec(function(err, user) {
if (err) return next(err);
if (!user) return next(new Error('Failed to load User with email ' + email));
req.user = user;
next();
});
};
exports.createResetPasswordEmailLink = function(req, res) {
var resetPassword = new ResetPassword(req.body);
resetPassword.resetId = new User().makeSalt();
**resetPassword.user = req.user._id; // currently req.user is null**
console.log(resetPassword.userId);
resetPassword.save(function(err) {
if (err) {
// handle error
}
res.status(200);
return res.redirect('/');
});
};
Following is my resetPassword schema
var ResetPasswordSchema = new Schema({
created: {
type: Date,
default: Date.now
},
resetId: {
type: String,
default: '',
trim: true
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
My routes is defined as follows
// Setting up the users resetpasswordlink
app.route('/createresetpasswordemaillink')
.post(users.createResetPasswordEmailLink);
I could solve this issue with app.params. App.params is exactly defined for this kind of usage.
I added
// Setting up the userId param
app.param('email', users.userByEmail);
to my routes and it automatically executed this function before the req is passed on to regular controllers.
From the documentation, App.param is defined as
app.param([name], callback)
Map logic to route parameters. For example when :user is present in a route path you may map user loading logic to automatically provide req.user to the route, or perform validations on the parameter input.