I am looking at some code from someone else for learning purposes. The way they're mounting routes is vague to me.
app.use('/dist', express.static(path.join(CURRENT_WORKING_DIR, 'dist')))
// mount routes
app.use('/', userRoutes)
app.use('/', authRoutes)
app.use('/', postRoutes)
The confusing part for me is how they're using '/' and using app.use. I'm used to doing it with app.get() and on top of that you specify the route instead of putting '/' everywhere. How does this work? Is this better practice?
The repo I'm looking at is https://github.com/shamahoque/mern-social/tree/master/server
Writing routes directly can be confusing and difficult to manage if there are large number of routes. So according to MVC pattern, the application is divided into modules/logical blocks based on functionalities they perform. For example, a simple hospital management system can have authentication, billing, payroll , medical-stock , patients etc modules (imaginary). If you are building application using MVC pattern, the common practice is to write controller for each of the module. Express provides something called middleware also called as Router to attach these controllers to respective API routes (Imagine it as a sort of map that connects each route to respective controller).
Once you define routes for each of these modules through middleware, you use those routes with your application. These routes handle requests and send parameters to controller to process.
You can learn how to use Middleware and Routers here : https://www.tutorialspoint.com/expressjs/expressjs_routing.htm
Regarding quality of code, dividing the code into modules and using routers to connect them is less tedious for others to understand. It also provides a good view of the application and it becomes easier to add new modules / functionality.
You can read more about building production-ready express app here :
https://www.freecodecamp.org/news/how-to-write-a-production-ready-node-and-express-app-f214f0b17d8c/
Related
An Angular 2 app uses the following code to load an array of routes:
export const routing = RouterModule.forRoot(myRoutes);
Currently, the myRoutes array is defined in the Angular 2 app, and works perfectly. But this assumes that routes have been defined statically in the client app.
How can the myRoutes array be fed into RouterModule.forRoot(myRoutes) from a source that would allow users do define routes and content from a user interface in a separate administration app? This would involve feeding the user-defined routes through a backend server.
I figured out how to send a data argument into each Route object in the myRoutes array, so that the same component can be re-used for multiple routes by sending different config into the same component from each route. But how can the routes array be imported from an external data store in a backend server?
This link indicates that I am describing a feature request. However, There MUST be some way to have UI-based content management in Angular 2 without having to resort to third party tools. What is a minimalist approach to importing an array of routes into RouterModule.forRoot(myRoutes) from a backend server?
You could try using dynamic component loading. The docs for it are here: https://angular.io/guide/dynamic-component-loader
I have not tried it ... but it does not look like it does exactly what you want. It does not seem to provide a way to add dynamic routes. But it does allow adding dynamic components.
Also, as per the link you defined, this is an issue with the CLI and its dependence on Web pack and AOT. You may be able to achieve more of what you want using SystemJS as your module loader.
I have the following Node Express routes...
get('/api/dogs')
get('/api/dogs/:id')
get('/api/dogs/breeds')
You can probably see the problem already. The routing gets confused when calling the 'breeds' route thinking I am trying to call the 'dogs/:id' route.
Is there a way to get around this? Or should I just create a unique route, something like 'api/dog-breeds'? I'd like to keep them all under the same resource because I am using the Express' modular 'router' object.
Is it okay for a site to use Express for handling the routing when using Server side rendered React templates rather than React Router?
I am looking to use Fluxxor similar to this example for my components and stores/actions. Then I was planning to use Express router to handle the page routing server side, and on each route render the desired component to string. In this basic example below my app.js is a simple todo example using Flux but in production it would likely be a top level component appropriate for the routed page. e.g. /products would be a product component, with its subcomponents.
Here is my basic server.js file
var express = require('express');
var React = require('react');
var App = require('./app');
var app = express();
var port = 4580;
// include my browserify bundle.js
app.use('/public', express.static(__dirname + '/public'));
app.get('/', function(req, res) {
/* each route will render the particular component to string. */
var markup = React.renderToString(App());
res.send(markup);
});
// I will seperate my views out like this
// app.get('/products', product.list);
// app.get('/users', user.list);
// app.get('/products:id', product.list);
My basic server side render approach is here if that helps.
So as I was saying, Is it okay to use Express for the routing, as I am finding React Rouuter to be quite complex, and it just seems easier to have routes on the server, and to render each page with its components server-side.
Am I losing anything else here other than the complexity of handling the routing in Express rather than React Router? As I think I can handle that, but want to make sure I haven't messed up the point of server side rendering with React by just using Express to render to string based on different routes.
Just to be clear, I'm okay with the issues which React Router aims to solve, and understand that I will be doing something similar to what was suggested in the React Router overview as being problematic in the long run.
// Not React Router API
otherRouter.route('/', function () {
React.render(<DashboardRoute/>, document.body);
});
otherRouter.route('/inbox', function () {
React.render(<InboxRoute/>, document.body);
});
otherRouter.route('/calendar', function () {
React.render(<CalendarRoute/>, document.body);
});
While one level of shared UI like this is pretty easy to handle, getting deeper and deeper adds more complexity.
I am basically assuming that I can handle this complexity okay, whether that is true or not, I guess I will find out in time.
Sounds like you are trying to make your website isomorphic—rendering static markup on the server, attaching event listeners on the client.
The approach I use for my projects is embedding client-side javascript in the server-rendered string, so that the same props are passed down and re-rendering is not required on the client.
It seems to be very complicated to explain with only a few snippets of code, so check out this template I created for this purpose. There's also a tutorial about this topic here.
I m actually developping a REST API using Node.js and Express 4.0 and I wanted to clarify something.
The service is actually working, but in a single javascript file, and I m looking for a good way to cut it into multiples parts.
I was thinking about MVC, but with the actual route system, what is the controller ? Is it the declaration function of the route ?
How can I separate the different route into multiple files ? (like user_routes, billing_routes) etc... I know how to export module etc... but having app = express() in multiple file seems to not work (different instanciation)
And where to start to the listen the part ?
These are beginner questions, but please, but explicit :-)
Thanks for advance
You can check out some these examples:
mvc: https://github.com/visionmedia/express/tree/master/examples/mvc and
route-separation: https://github.com/visionmedia/express/tree/master/examples/route-separation
Also here there are 2 good posts on SO about the subject:
https://stackoverflow.com/a/13611448/2846161
ExpressJS How to structure an application?
I'm quite new to node.js, and pretty new to Javascript (I don't count simple animations with jQuery as js). As a web-developer, I'm moving from PHP/MySQL to Express/mongo.
I like the idea of things being neat - as long as there isn't a noticeable loss in performance. As node is so rapidly developing, I'm finding it hard to find specific opinions and answers to my routeing methods for the current version of node (Most posts I find seem to be irrelevant and older than 2 years).
|- app.js
|- routes
|- blog.js
I'm using blog.js as the gateway for all blog-related stuff. This includes registering GET and POST requests with a function, and handling page-rendering.
This is all fired up with one call.
My app.js has the following:
... //basic express installation
var db = ... //mongoose database connection
require('./routes/blog')(app, db, '/blog'); //starts the blog up
blog.js looks like this:
var db = null;
var basedir = null;
module.exports = function(app, _db, _basedir){
db = _db;
basedir = _basedir;
app.get (basedir, pages.home );
app.get (basedir + '/show/:id', pages.getBlog );
/*app.get(basedir + '/*', function(req, res) {
res.redirect(basedir);
});*/
};
var pages = {
home : function(req, res) {
// whatever
}
, getBlog : function(req, res) {
// whatever
}
}
I know this works - my question, is if this is conventional? Is it something that isn't recommended? Is it memory-wasteful? Why do people place app.gets in app.js rather than an external file? What are the current mainly used routeing methods (I develop multiple small applications all on the same server, hence my wish for my app.js to be as minimal as possible).
The way you've outlined is perfectly acceptable, and in my mind, preferred to just having one big app.js file with all your routes and everything else in it.
Many people take the separating of code much further than what you've outlined, especially when trying to follow MVC and MVC-like patterns.
For example, here's a boilerplate project I'd been working on that might even go a little overboard on separation. It's not a finished product, just something I was playing with that took some of the different bits I liked from other boilerplates, frameworks, etc. I've learned some things since then and I might adjust it at some point.
NemoJS - My node/express/mongoose/jade/stylus/twitter_bstrap boilerplate project
One thing to keep in mind is the more you separate it, the more difficult it CAN be to track down problems. Not a good enough reason for not staying organized though. Which is essentially what our goal is, right?