Organization of various requests in Node.js

I am new to Node.js (and Express) and I am trying to figure this out. Let's say I have a website with 3 pages (maybe GET or POST): / , /page1 , /page2 . What should I do so that each page is processed by a separate JS file?

 app.all('/', function(request, response) { // Get home.js to handle this request and response }); app.all('/page1', function(request, response) { // Get page1.js to handle this request and response }); app.all('/page2', function(request, response) { // Get page2.js to handle this request and response }); 

Even better, is there a way to define a wildcard, so there aren't many repetitions? Something like that:

 app.all('*', function(request, response) { // Get *.js to handle this request and response. * is whatever the URI string is }); 
+4
source share
2 answers

Continuing the discussion with @Alex. Here is how I did it. Any info?

 // app.js var EXPRESS = require('express'); var URL = require('url'); var PATH = require('path'); var app = EXPRESS.createServer(); app.all(/^\/([a-zA-Z0-9-]+)$/, function(request, response, next) { var page = request.params[0]; if (PATH.existsSync(__dirname + '/' + page + '.js')) { require('./' + page).handleRequest(request, response, next); } else { next(); } }); app.all('*', function(request, response) { response.send('Catch all'); }); // --- truncated for brievity // page1.js exports.handleRequest = function(request, response, next) { response.send('Howdy!'); }; 
0
source

The trick is that the app is local to the file that creates it. Thus, you should get this object in the area of ​​other files.

Every other file must export funciton through which you can pass your application instance so that it can register new routes. This approach should work.

 // home.js exports.register = function(app) { app.all('/', function(request, response) { ... }); }; // page1.js exports.register = function(app) { app.all('/page1', function(request, response) { ... }); }; // page2.js exports.register = function(app) { app.all('/page2', function(request, response) { ... }); }; //server.js - setup the app app = express.createServer(); require('./home').register(app); require('./page1').register(app); require('./page2').register(app); 

And for the second part of your question, do you want to share some tuning methods?

 app.all('*', function(req, res, next) { res.header 'x-snazzy-header', 'Im so snazzy' next() }); app.all('/page/:id', function(req, res) { res.send('content for page #'+ req.params('id')); }); 

First you can use * or named parameters like /users/:id to match the range of routes. And if you want to make some general settings, you can actually follow 2 routes. The route handler accepts the optional third argument next . When called, he will try to find the next route to match. This way you can customize things like generic headers for a bunch of routes.

+4
source

Source: https://habr.com/ru/post/1399290/


All Articles