Add Routes at Runtime (ExpressJs) - javascript

I would like to add routes at run time. I read that its possible but I am not so sure how. Currently I using the following code:
var app = express();
function CreateRoute(route){
app.use(route, require('./routes/customchat.js'));
}
And customchat looks like
var express = require('express');
var router = express.Router();
router.route('/').get(function (req, res) {
var url = req.baseUrl;
var roomname = url.substring(url.lastIndexOf('_') + 1);
res.render('chat', { name: roomname , year: new Date().getFullYear().toString()});
});
module.exports = router;
When I call the method CreateRoute before I start listening it will link the route. But when I do it at runtime it wont create a new route.
My goal is to add routes add runtime. I will generate an path like /room_Date. And this should be added at runtime using the template customchat.
I am using express version 4.13.
Thanks in advance for your help.

customchat.js should called customChat.js and be
const customChat = (req, res) => {
const { name } = req.params;
const year = new Date().getFullYear().toString();
res.render('chat', { name , year });
}
module.exports = customChat
then when you create your app
const express = require('express')
const customChat = require('./routes/customChat.js')
const app = express()
app.use('/chat/:name', customChat)
See the official Express routing docs for more information.

Related

How to use class methods without useing "type": "module" in node js

js developer.
I am making express and jade web app. Now I am trying to call class method in index.router.js from login.controller.js, I have been looking for a way to call the method without adding "type": "module" in package.json. This is because my teacher said I should avoid using it for now. I have been looking for a solution for this, but I haven't figured out how. Thanks for reading!
Here's my code:
//This is index.route.js
const express = require('express');
const app = express();
const IndexRouter = express.Router();
const LoginController = require('../controllers/login.controller')
IndexRouter.use('/', LoginController.login())
module.exports = IndexRouter
//This is login.controller.js
module.exports = class LoginController{
async login (req,res) {
res.send("Login Page")
}
}
Create Class Objects and use class objects to access class
methods
In index.route.js
const express = require('express');
const app = express();
const IndexRouter = express.Router();
const LoginController = require('../controllers/login.controller')
const loginController = new LoginController();
IndexRouter.use('/', loginController.login())
module.exports = IndexRouter
In login.controller.js
class LoginController {
async login(req, res) {
res.send("Login Page")
}
}
module.exports = LoginController;
For Ex.
class LoginController {
login(req, res) {
console.log("LoginController Login");
}
}
const loginController = new LoginController();
loginController.login();
Or can directly access Login function without using class
In index.route.js
const express = require('express');
const app = express();
const IndexRouter = express.Router();
const { login } = require('../controllers/login.controller')
IndexRouter.use('/', login()); // or use('/', login) if using middleware
module.exports = IndexRouter
In login.controller.js
async function login(req, res) {
res.send("Login Page")
}
module.exports = {
login
};

Router creation in API, SP response

I'm starting to develop an API but I don't have a high level of programming. I am occupying express and node.js. I am trying to add the response of the call to the SQL_SP_STATUS to a Router, in order to get its results after a call:
var connectionStatus = async function (stpName = process.env.SQL_SP_STATUS) {
const response = await sqlDB.getStatus(dbSQL,stpName);
return response;
}
When trying to make the Router from some examples that I have, it does not work, I have set it up as follows:
router.get('/test', async function () {
stpName = process.env.SQL_SP_STATUS;
let connectionStatus = stpName ;
const response = await sqlDB.getStatus(dbSQL,stpName);
return response;
});
The truth is that I do not know the correct way to do it, please I need advice.
Thank you very much in advance, I will be attentive to your answers.
Regards!
It depends on how you want to do it. You can have your routes defined e.g.
testroute.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.json({});
});
module.exports = router;
Have a router file that includes all your routes.
const express = require('express');
const router = express.Router();
router.use('/api/test', require('./routes/testroute'));
module.exports = router;
and maybe in your express file have something like
const express = require('express');
const app = express();
app.use(require('./routes'));
Read the documentation for better understanding.
express documentation

404 Cannot POST Using Express

I´m trying to create an API Rest in NodeJs with Express.
I have my index.js with the following code:
const express = require('express');
const routesV1 = require('./routes/v1/index');
const app = express();
routesV1(app);
app.listen(4000, () => {
console.log('Running on port: 4000');
});
then i have a routes folder with another "index.js" and a "usersRoutes".
Here´s the code of the userRoutes:
const express = require('express');
const userController = require('../../controllers/v1/UserController');
const router = express.Router();
router.post('/create', userController.createUser);
router.post('/update', userController.updateUser);
router.post('/delete', userController.deleteUser);
router.get('/get-all', userController.getUsers);
module.exports = router;
and the code of the index.js into the routes folder:
const userRoutes = require('./UserRoutes');
const productRoutes = require('./ProductRoutes');
module.exports = app => {
app.use('api/v1/users', userRoutes);
};
but when i´m consuming via Postman, with the following url: http://localhost:4000/api/v1/users/create I´m receiving a 404 error code.
Can anybody help me? thanks
I resolved it adding '/' to the route in routes/index.js
const userRoutes = require('./UserRoutes');
const productRoutes = require('./ProductRoutes');
module.exports = app => {
app.use('/api/v1/users', userRoutes);
app.use('/api/v1/products', productRoutes);
};

how to save json object from third party api

I'm having trouble figuring out how to save a json object from a third party api to my personal localhost mongodb. I believe I'm supposed to create another method within the api controller but am not sure what kind of method should be used any help would be great thanks!
Here is my code sorry if this is a dumb question.
//server.js
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var mongoose = require('mongoose');
var Router = require('./routes');
var morgan = require('morgan');
var port = process.env.PORT || 3000;
var app = express();
//database connect
mongoose.connect('mongodb://localhost/Emagispace')
app.use(
express.static('views'),
bodyParser.json(),
bodyParser.urlencoded({extended : true}),
morgan('dev')
);
Router(app);
app.listen(port, ()=>{
console.log(`Server running on ${port}`);
//Routes
var API = require('./controllers/api');
module.exports = (app)=>{
app.get('/', (req, res)=>{
res.sendFile('index.html', {root : './views'});
});
app.get('/api/emagispace', API.product)
}
//API controller
var request = require('request-promise');
var baseURI = 'example';
module.exports = {
product : (req, res)=>{
request({
method : 'GET',
url : `${baseURI}/api/emagispace/${req.query.products}`
})
.then((resp)=>{
console.log('Product list : ', resp);
res.send(resp).save();
})
}
}
In order use mongoose for saving the documents you'll need to specify the Schema first.
//product-model.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ProductSchema = new Schema({
name: String,
price: String,
//And all other data you need
});
var Product = mongoose.model('Product', ProductSchema);
Also you can do validation and much else. Please see the docs.
Then you can use .insertMany to save them in one shot or iterrate over your documents:
var Product = require('../models/product-model.js');
...
.then((resp)=>{
//I assume that resp is an array of products here
console.log('Product list : ', resp);
//Go over your product list and save them
for (var product of resp) {
var p = new Product(product);
p.save();
}
//OR
Product.insertMany(resp);
res.send(resp);
})
After this you'll have products collection in your local db.
Also you can warp these calls into a method if you want.

How to use nested middleware in express.js

I want to make a change from the actual structure of my code. This is the actual code i have:
//index.js
var routes = require('./routes');
var subdomain = require('express-subdomain');
//require express app with settings
var app = require('./app');
//export the application
module.exports = app;
// routes request like endusers-api.mydomain.ext/
app.use(subdomain('endusers-api', routes.apis.endusers));
// routes request like mydomain.ext/
app.use(routes.webapps.endusers);
//routes/index.js
var apis = {endusers: require("./apis/endusers")}
var webapps = {endusers: require("./webapps/endusers")}
var routes = {apis: apis, webapps: webapps}
module.exports = routes;
//routes/apis/endusers
var express = require('express');
var route = express.Router();
var logger = require('../../lib/logger');
route.get('/', logger("endusers-api-access"), function(req, res, next) {
res.json({
"name" : "Endusers API"
});
});
module.exports = route;
//routes/webapps/endusers.js
var express = require('express');
var route = express.Router();
var logger = require('../../lib/logger');
route.get('/', logger("endusers-webapp-access"), function(req, res, next) {
res.render('endusers/index', {title: 'Homepage'});
});
module.exports = route;
Now I want to change the above code to this (feel free to tell me if this is a good approach of doing things in Node.js or not):
//index.js
var middlewares = require('./middlewares');
var app = require('./app');
module.exports = app;
//i want to change to this
app.use(middlewares.endusersApi);
app.use(middlewares.endusersWebapp);
//Stuff for creating server and listening...
//middlewares/index.js
var middlewares = {
endusersApi : require("./apis/endusers"),
endusersWebapp : require("./webapps/endusers")
}
module.exports = middlewares;
//middlewares/apis/endusers.js
//TODO
//middlewares/webapps/endusers
//TODO
How should I write the TODO portions above. It look like we will need nested middlewares (a middleware calling another middleware). Please, your suggestions.
I found the answer using by express.Router().all() method.
//middlewares/apis/endusers.js
var routes = require('../../routes');
var express = require('express');
var middleware = express.Router();
middleware.all('/',subdomain('endusers-api', routes.apis.endusers));
//the two next lines are alternatives to the line above
//middleware = subdomain('endusers-api', routes.apis.endusers); //can assign only one route
//middleware.use(subdomain('endusers-api', routes.apis.endusers)); // can use many routes
module.exports = middleware;
//middlewares/webapps/endusers.js
var routes = require('../../routes');
var express = require('express');
var middleware = express.Router();
middleware.all('/', routes.webapps.endusers);
//the two next lines are alternatives to the line above
//middleware = routes.webapps.endusers; //can assign only one route
//middleware.use(routes.webapps.endusers); // can use many routes
module.exports = middleware;

Categories