Adding Routes to ExpressJS App from Modules - node.js

Trying to figure out how routing middleware works on ExpressJS.
What I am trying to solve is:
app has some basic routing in the /index.js
app will have some modules that will add its own routes and handlers (eg. hello & world)
I have added different routing options to see what works - but I have overcooked.
https://codesandbox.io/s/flamboyant-mcnulty-7b79x

Add the hello and world routes like this:
app.use(hello());
world.setup(app);
For some reason, the connect-history-api-fallback module will cause to nothing matched route.
If you comment the code use history middleware:
// app.use(history());
Now, you can access the hello route via https://ncpt4.sse.codesandbox.io/hello and access the world route via https://ncpt4.sse.codesandbox.io/world.
example link: https://codesandbox.io/s/amazing-worker-ncpt4

Related

Implementing Passport Local Authentication in Backend

I am trying to implement the passport local authentication in my backend. It is a todo app which is built with the help of the MEAN stack. Unfortunately, I am facing some problems implementing it. The folder structure is
In Controllers folder, the controllers for the various routes are present.
In routes folder, the file "api.route.js" contains the main route. I want to implement authentication here such that no further routes can be accessed if the user is not autheticated.
In the api subfolder, the different routes are configured.
In the config subfolder, the passport local strategy is defined.
Another new problem I have noticed is that the routes after todo are not detected.
Example : localhost:3000/api/todos
localhost :3000/api/todos/login
route does not work. It says Error 404. Every other sub routes are the same. Any help which will help me to implement will be appreciated. The github profile for this project is :
https://github.com/AritraWork97/TODO-FULLSTACK
The main folder is Todo Backend, it contains the backend code
To, protect routes in back-end I think express-jwt will be handy.
Initialize it like this,
const jwt = require("express-jwt");
const auth = jwt({secret: jwt_secret});
Then put the auth middleware before a route that you want to protect.
router.get("/secret/:uid", auth, profileCtrl.secret);

How to prevent express server from serving api routes from the static folder

Hi I need some help with how express handles routes.
In setting up my express app, I have something like this:
app.use(express.static('public'));
Next, I mount some api routes:
app.use('/api', myrouter);
app.get('*', function(req, res) {
res.sendFile(path.resolve('public/index.html'));
});
But, when the frontend requests data via an api route, e.g. at 'localhost:3000/api/things', I am seeing in the Express debug logs that at some point (unsure when) it actually tries to serve this request as a static file, like:
send stat "C:\myproject\public\api\things" +230ms
Even though this folder doesn't exist in 'public' and should be solely handled by my api. FYI, the handler for /api/things route is only implemented for the GET method, and does get invoked at some point.
How do I stop express server from also trying to serve api requests from the static folder?
Thanks very much.
Answering my own question... which appears to be a duplicate of this one:
`express.static()` keeps routing my files from the route
So the answer is this one: https://stackoverflow.com/a/28143812/8670745
In short, the app.use() declarations that mount your api routers should appear before the app.use() statements which tell express.static where to serve your static files from. This way, the latter acts as a catchall AFTER api route handling is done. Router engine order matters...
Your answer is misinformed, or rather you've misinterpreted the problem. Your original configuration:
app.use(express.static(__dirname + 'public'));
app.use('/api', myrouter);
Looks absolutely fine because there's no clash between the routes. The threads you've linked too aren't really the same, and I can see why moving the routes in those cases would have worked.
The only thing I'd say is your path to your static folder isn't reliable, you should really use path.join, or actually in your case you can just do express.static('public') - express will infer the folder your app is served from.

Express.js or angular for handling routes in a MEAN application?

I am totally new to everything Nodejs/express/angular, and I just ran into a question that bothers me.
When you have a MEAN stack, it seems that routes can be handled by both Express.js and Angular.
Angular:
For instance, if I define a route in Angular, I can do it like this:
var app = angular.module("app", []).config(function($routeProvider) {
$routeProvider.when('/login', {
templateUrl: '/templates/login.html',
controller: 'LoginController'
});
$routeProvider.when('/front', {
templateUrl: '/templates/front.html',
controller: 'FrontController'
});
$routeProvider.otherwise({redirectTo: '/front'})
});
But with express.js I do:
app.get('/',function(req,res){
res.sendfile('templates/angular.html');
});
So my question is:
When do you use angular routing, and when do you use express routing?
(I might miss something very obvious here, but I hope you can point it out)
Those two serve different purposes on a single page app.
The app would do all the CRUD (endpoints where you create/read/update/delete your stuff, for example: projects, users, bills, etc). Also it would do all the authentication stuff (like /login and /register).
All of that needs routes, because you would want something like /api/users to grab all your users. All those routes, AKA CRUD routes and authentication routes goes into express.js router. Why there? Because those are routes of the backend.
On the other hand, you have your angular application, which contains the visual part of your application and there you want some routes. You want / to point to your home, you would want /users to have a page where you list your users or even /users/add to have a page with a form to add new users.
You could see it this way:
Backend routes (express ones): Those are the routes that an end user won't have to know about or even use them (your angular app will use them to communicate with the backend to work with its data but an end user wouldn't put them directly on the browser)).
Frontend routes (angular ones): Are the routes that maps to different pages of your application and because of that, end users can use them to access some parts of your application directly.

Ember and Express: let Ember handle routes instead of Express?

This might be a dumb question, but I'm serving an Ember app I made using ember-cli on an Express server, but when I try to access various routes, my Express app errors, saying that no route exists (which is true, because I defined the routes in Ember, not Express). How should I resolve this, and is this normal behavior?
My Ember router:
Router.map(function() {
this.route('index', {path: '/' });
this.route('portkey');
this.route('login');
});
My Express routes are just an API that do not serve any of the Ember routes, since localhost:1234 will automatically load index.html.
I've never had a problem using the Ember Router instead of the Express router. All I do is have 1 express route (for '/') which displays my Ember application index.html (well actually index.ejs) page. Not promising this is the right way to do it, but it's how I do it and it works for me.
So start with this.
app.get('/', function(req, res) {
res.render('index', {});
});
That's your express route. Now your ember routing.
App.Router.map( function() {
this.route("about", { path: "/about" });
this.route("favorites", { path: "/favorites" });
});
So as of now you have a routing structure that looks like the following:
yourdomain.com/ --> index.ejs displayed via express routing
/#/ --> this is the ember index route
/#/about --> this is the ember about route
/#/favorites --> this is the ember favorites route
Within the index.ejs file you have the basic ember file linking to your ember application.
Now onto your linking problems...
If you use the ember router, then make sure you are linking to your different routes the correct way. (Remember, ember routes start with /#/someroute).
So your links in handlebars should be something like:
{{#link-to 'some_page'}}Go to some page{{/link}}
NOT
Go to some page
Using the second, express would be trying to handle the routing but by using the first, ember is handling the routing.
So if you really think about it, you can have as many ember applications as your little heart disires because each ember application is linked to that current page in the express routing.
For example on my website, I use two routes (plus a bunch of REST routes obviously): login.ejs and index.ejs.
So for my site, I have the following routes:
mysite.com/
/#/
/#/budget
/#/history
/#/profile
/#/logout
mysite.com/login#/
#/register
#/forget
I hope this helps you a little bit.
EDIT
/#/ is a convention to tell ember you are routing via its router.
Think of it like this: Ember is a single-page framework. So when you link from page to page in ember, you aren't truely changing pages. You are just removing dom elements and replacing them with new ones. But if you go to /budget on the server, you are now going to a whole new page, not just the /#/budget section of the ember application.
I think you are just confusing what the ember router really is.
I had similar issues when trying to directly access any part of my Ember project other than index.html. From there I could easily navigate where I wanted, but it meant that providing someone a link or refreshing the page would fail.
Example: /accounts would fail.
/#/accounts would successfully redirect to /accounts however refreshing still would not work.
Solution:
Router.map(function() {
this.route('accounts');
});
Router.reopen({
location: 'hash'
});
Now all of my links are prefixed with # such as /#/accounts, refreshing and direct-linking works as expected.

Express router conflicting with Backbone pushstate

An Express / route serves my Backbone's app index.html.
I'm using pushstate in Backbone but the routes that Backbone should handled are being handled by express, giving 404 responses.
How can I setup Express to serve the index.html but to delegate other routes to Backbone?
In this situation you have multiple options:
You can have a server that handles the same routes as the client does and returns the same results. It is hard to implement but it gives a good url. Github did this.
Always return index.html and handle the route client side. (That is somewhat ugly and hard to maintain)
Don't use pushstate. Amen.
You can use /* approach. Just have it as the last route. That way the other routes such as any service API calls will be matched before the catch all route of /* is matched. This is also how Backbone handles its routes.

Resources