How to export a variable in node js that initialize after click on button?
File from which i export:
router.post('/', (req, res) => {
let settings = req.body;
module.exports.settings = settings;
res.send('/testroom');
});
File from which i import
let { settings } = require('./pretest');
router.get('/', async (req, res) => {
console.log('settings', settings);
res.sendFile(path.join(__dirname, '../public/html/testroom.html'));
});
you are almost got it right, but when you get the value on the other route it will be already declared and initialized with the first value of the setting
router.post('/', (req, res) => {
let settings = req.body;
exports.settings = settings;
res.send('/testroom');
});
router.get('/', async (req, res) => {
// here its scoped with route when its called its gets the current value
let { settings } = require('./pretest');
console.log('settings', settings);
res.sendFile(path.join(__dirname, '../public/html/testroom.html'));
});
Related
How to set verification of session for all routes?
if(req.session.lang) req.session.lang
else req.session.lang = "pt";
const tradutor = require('../scripts/lang/lang-'+req.session.lang+'');
var traduPT = new tradutor();
this is my code. i want use for check in all routes, maybe something like adding the code and just applying the request on the routes, but how and where to do this code outside the routes?
You can create route-specific middleware.
// validate.js
export const validateSession = (req, res, next) => {
// if the user is logged in, continue
if (req.session.isLoggedIn) return next();
// otherwise, don't continue and go back to the /home route
res.redirect('/home');
};
Then pass it in as the second argument when defining your route:
// main.js
import { validateSession } from './validate.js';
app.get('/dashboard', validateSession, (req, res) => { /* ... */ });
app.get('/login', validateSession, (req, res) => { /* ... */ });
app.get('/foo', validateSession, (req, res) => { /* ... */ });
I am trying to import registerUser function inside router.post, in the same file in which i have exported its function (registerUser) so that it can be used outside this module also but it says
TypeError: require(...).registerUser is not a function
please have a look -
**user.js // express route for 'api/user/signup/ --------**
const router = require('express').Router();
const userModel = require('../models/user');
exports.registerUser = async (req, res, next) => {
console.log('in registeruser')
}
router.post("/signup", (req, res, next) => {
require('./user').registerUser(req, res, next);
console.log('in signup')
next();
})
module.exports = router;
You shouldn't require the same file you're already in.
Instead just create the function, and then later on export it. Your code would then look like this.
const router = require('express').Router();
const userModel = require('../models/user');
async function registerUser(req, res, next) {
console.log('in registeruser')
}
router.post("/signup", (req, res, next) => {
registerUser(req, res, next);
console.log('in signup')
next();
})
exports.registerUser = registerUser;
module.exports = router;
Not sure why you are trying to reimport it, just declare it as a variable and use it directly, you can still export it
const router = require('express').Router();
const userModel = require('../models/user');
const registerUser = async (req, res, next) => {
console.log('in registeruser')
next();
}
// since registerUser is also middleware, you can pass it as a param to post
router.post("/signup", registerUser, (req, res, next) => {
console.log('in signup')
next();
});
exports.registerUser = registerUser;
If you want to use the registerUser in the same file, you don't need to export it.
const router = require('express').Router();
const userModel = require('../models/user');
registerUser = async (req, res, next) => {
console.log('in registeruser')
}
router.post("/signup", (req, res, next) => {
registerUser(req, res, next);
console.log('in signup')
next();
})
module.exports = router;
If you want to use the registerUser in other modules, simply export it by modifying your exports statement
module.exports = {router, registerUser}
I am writing my own app (both of back and frontend). I want to ask you guys if I am doing it in the right way.
I want to split server.js to a few files (in PHP I would use include() for it) but I am not sure if it is the right way.
Here is some code example:
const app = require('express')(),
fs = require('fs'),
http = require('http').Server(app),
io = require('socket.io')(https),
path = require('path'),
login_user = require('./routes/login_user'),
add_user = require('./routes/add_user'),
logout = require('./routes/logout');
app.post('/login_user', (req, res, next) => {
login_user.go(req, res, next);
});
app.post('/add_user', (req, res) => {
add_user.go(req, res);
});
app.get('/logout', (req, res) => {
logout.go(req, res);
});
Please note that's not the whole code and I want to focus on spliting "routes" or "paths" to a few files. For example a whole API login system is in /routes/login_user.js file (exported).
Now I have got so many paths and code is looking a little bit weird.
app.post('/check_balance', (req, res) => {
check_balance.go(req, res);
});
app.post('/add_incoming', (req, res) => {
add_incoming.go(req, res);
});
app.post('/add_outgoing', (req, res) => {
add_outgoing.go(req, res);
});
app.post('/add_category', (req, res) => {
add_category.go(req, res);
});
app.post('/change_settings', (req, res) => {
change_settings.go(req, res);
});
app.post('/login_user', (req, res, next) => {
login_user.go(req, res, next);
});
app.post('/add_user', (req, res) => {
add_user.go(req, res);
});
app.post('/verify_user', (req, res) => {
verify_user.go(req, res);
});
app.get('/logout', (req, res) => {
logout.go(req, res);
});
app.get('/check_settings', (req, res) => {
check_settings.go(req, res);
});
app.get('/check_categories', (req, res) => {
check_categories.go(req, res);
});
app.post('/remove_categories', (req, res) => {
remove_categories.go(req, res);
});
app.get('/check_incomings', (req, res) => {
check_incomings.go(req, res);
});
app.get('/check_outgoings', (req, res) => {
check_outgoings.go(req, res);
});
app.get('/check_both', (req, res) => {
check_both.go(req, res);
});
app.get('/check_outgoings_chart', (req, res) => {
check_outgoings_chart.go(req, res);
});
app.get('/check_incomings_chart', (req, res) => {
check_incomings_chart.go(req, res);
});
app.post('/remove_incomings', (req, res) => {
remove_incomings.go(req, res);
});
app.post('/remove_outgoings', (req, res) => {
remove_outgoings.go(req, res);
});
Make your server.js as simple as possible and extract all your routing logic to separate folder (possibly name it "routes"). If you also want to define yours schema, put it in separate folder ("models"). A complete solution can be like this:
in Model Folder:
user.js
const mongoose = require("mongoose"); // In case if you want to use MongoDB
const userSchema = new mongoose.Schema({
name: { type: String, required:true },
email: { type: String, required: true },
password: { type: String, required: true },
});
exports.User = User;
In routes folder:
users.js
const { User } = require("../models/user");
const router = express.Router();
//define your routes here
router.get('/', async(req,res)=>{
const users = await User.find();
res.send(users)
});
module.exports = router;
And finally in your server.js
const app = require('express')(),
fs = require('fs'),
http = require('http').Server(app),
io = require('socket.io')(https),
path = require('path'),
users = require('./routes/users');
app.use("/api/users", users); //With this API Endpoint you can access it like http://{your_domain}/api/users
If you want to make it more clean, you can wrap all routing paths to another folder. Lets call it "startup".
with this you can do like this.
in your startup folder:
routes.js
const users = require("../routes/users");
module.exports = function(app) {
app.use("/api/users", users);
//add all routes here
}
Then in your server.js
require("./startup/routes")(app); //all routes will be imported
I think this is what you need.
Let's say that there is a file called routers/login.js:
var express = require('express');
var router = express.Router();
router.get('/login', function(req, res) {
// do something
});
then app.js:
...
var login = require('./routes/login');
app.use("/login", login)
Put all the routes files in a folder with multiple files like User_routes.js can contain routes related to user and so on.
Also all you need to then is to export these routes from each file by using module.export.your_module and include them in your server file like in user routes :
// Login Page
router.get('/login', (req, res) => res.render('login'));
// Register Page
router.get('/register',(req, res) => {
res.render('register'); });
then import it as
module.exports = router;
also include it as :
app.use('/users', require('./routes/users.js'));
app.use('/',(req,res,next)=>{
console.log('I should handle it Now.');
res.render('404');
});
I am trying to use an asynchronous function in my Node API controller, but am receiving an error from my 'error-handler' middleware.
TypeError: fn is not a function
at eval (webpack:///./app/middleware/errorHandler.js?:16:21)
It does not like my 'findAll' function exported from my controller, why is this not a function? Am I exporting the function correctly? Am I using async/await correctly? Do I need a polyfill for this? I understood that async/await was supported from Node v8. I am currently running Node v11.10 and Express v4.16.4.
Here is my routes file:
// routes.js
const verifyToken = require('../../middleware/verifyToken.js');
const errorHandler = require('../../middleware/errorHandler.js');
module.exports = app => {
const controller = require('../../controllers/controller.js');
app.get(`/collection`, verifyToken, errorHandler(controller.findAll));
}
Here is my controller:
// controller.js
exports.findAll = async (req, res) => {
const collections = await collection.find().populate('other');
res.send(collections);
};
Here is my middleware:
// errorHandler.js
module.exports = fn => {
return (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
};
Any help is greatly appreciated.
Im not sure but is errorHandler expecting fn to be the error? If so, why is it called passing (req, res next)?
I use following structure:
Router
// routes.js
const verifyToken = require('../../middleware/verifyToken.js');
const controller = require('../../controllers/controller.js');
var router = express.Router()
router.route('/collection').get(
verifyToken,
controller.findAll
)
module.exports = router
Controller
// controller.js
const asyncUtil = fn =>
function asyncUtilWrap(req, res, next, ...args) {
const fnReturn = fn(req, res, next, ...args)
return Promise.resolve(fnReturn).catch(next)
}
module.exports = {
findAll: asyncUtil(async (req, res, next) => {
const collections = await collection.find().populate('other'); // you can do try/catch here if you want to handle the error here
res.send(collections);
};
Then Error Handler usually goes at bottom of app.js (but you can place it at bottom of your router):
// app.js
app.use(function(err, req, res, next) {
res.status(err.status || 500)
res.send(err.message)
})
I believe this is how I would do it if I understand you correctly:
// routes.js
const verifyToken = require('../../middleware/verifyToken.js');
const controller = require('../../controllers/controller.js');
module.exports = app => {
app.get(`/collection`, verifyToken, controller.findAll);
}
// controller.js
exports.findAll = async (req, res, next) => {
try {
const collections = await collection.find().populate('other');
res.send(collections);
} catch(err) {
console.log(err); // up to you what to do with the error
next();
}
};
I have the following .post() request:
const express = require('express');
const router = express.Router();
const search_controller = require('../controllers/searchController');
const result_controller = require('../controllers/resultController');
//Search Routes
router.post('/', search_controller.search_create_post);
module.exports = router;
Could I add a second callback to it so that the first callback is run, then the second callback as such:
router.post('/', search_controller.search_create_post, result_controller.result_create_post)
Would I need a next() somewhere in those create functions? And could I also pass data from the search_create_post callback to the result_create_post callback? I would want to pass in the newly created Search object's id.
My current search_controller.search_create_post function is a such:
exports.search_create_post = (req, res, next) => {
let newSearch = new Search({ search_text: req.body.search_text });
newSearch.save((err, savedSearch) => {
if (err) {
console.log(err);
} else {
res.send(savedSearch);
}
})
};
You might be able to use like this (based on how your functions are written):
// option A
router.post('/', search_controller.search_create_post, result_controller.result_create_post)
// options B
router.post('/', search_controller.search_create_post)
router.post('/', result_controller.result_create_post)
If search needs to pass data to result, you could set req.search_data in search_create_post and then get the value in result_create_post.
Take a look at https://expressjs.com/en/guide/using-middleware.html. There are a few good examples on this page.
app.get('/user/:id', function (req, res, next) {
console.log('ID:', req.params.id)
next()
}, function (req, res, next) {
res.send('User Info')
})
// handler for the /user/:id path, which prints the user ID
app.get('/user/:id', function (req, res, next) {
res.end(req.params.id)
})
based on your comment below:
You might be able to do this...
exports.search_create_post = (req, res, next) => {
let newSearch = new Search({ search_text: req.body.search_text });
newSearch.save((err, savedSearch) => {
if (err) {
console.log(err);
} else {
req.searchData = savedSearch;
}
next();
})
};