Subdomain routing in loopback to multiple static files (angular apps) - node.js

I've got two angular 2 client apps that I'd like to serve from my loopback backend. I've been able to serve them successfully from subdirectories (www.mysite.com/subdirectory), but I'm trying to serve them from subdomains (www.subdomain.mysite.com).
Loopback doesn't seem to have a built in way to handle subdomain routing through the middleware or anywhere else that I can see. So I'm trying to accomplish the routing by matching the hostname in a url-not-found-handler that is set for final in the middleware.json file as such:
if (req.hostname.match(/subdomain1\./g)) {
console.log('requesting subdomain1 site')
res.sendFile(path.resolve() + '/dist/subdomain1/index.html')
} else if (req.hostname.match(/subdomain2\./g)) {
console.log('requesting subdomain2 site')
res.sendFile(path.resolve() + '/dist/subdomain/index.html')
} else {
next();
}
I've also got the static files in the middleware.json set up as such:
"files": {
"loopback#static": [
{
"name": "subdomain1",
"params": "dist/subdomain1"
},
{
"name": "subdomain2",
"params": "dist/subdomain2"
}
]
}
This seems to work in that it properly matches and sends the correct index.html file. I know it's the right index.html by inspecting in the browser.
But for some reason the actual angular app that gets served ALWAYS is whatever is first in the loopback#static array. If I have subdomain2 first, that will be shown for both subdomain1.mysite.com as well as subdomain2.mysite.com.
How can I fix this issue and serve a different apps based on the subdomain?

So I figured out a solution. Don't think loopback has a built in way of handling this, so got it to work with the following:
Cleared the files section from middleware.json
"files": {}
Used a combination of vhost and serve-static to deliver based on the subdomain
var vhost = require('vhost');
var serveStatic = require('serve-static');
var serveSubdomain1 = serveStatic('dist/subdomain1', {'index': ['index.html']})
var serveSubdomain2 = serveStatic('dist/subdomain2', {'index': ['index.html']})
app.use(vhost('subdomain1.mysite', serveSubdomain1));
app.use(vhost('subdomain2.mysite', serveSubdomain2));

Related

Wildcard subdomain info sharing between node server and Nuxt/Vue client

We are building a multi_tenant solution with NodeJS/Express for the back end and VueJS/Nuxt for the front-end. Each tenant will get their own subdomain like x.mysite.com, y.mysite.com, etc.
How can we make both our back end and front-end read the subdomain name and share with each other?
I have some understanding that in the Vue client, we can read suvdomain using window.location. But I think that's too late. Is there a better way? And what about the node /express setup? How do we get the suvidhaon info there?
Note that Node/Express server is primarily an API to interface with database and for authentication.
Any help or insight to put us on the right path is appreciated.
I'm doing something similar in my app. My solution looks something like this...
Front End: In router.vue, I check the subdomain to see what routes to return using window.location.host. There is 3 options
no subdomain loads the original routes (mysite.com)
portal subdomain loads the portal routes (portal.mysite.com)
any other subdomain loads the routes for the custom client subdomain, which can be anything and is dynamic
My routes for situation #3 looks like this:
import HostedSiteHomePage from 'pages/hostedsite/hosted-site-home'
export const hostedSiteRoutes = [
{ path: '*', component: HostedSiteHomePage }
]
The asterisk means that any unmatched route will fallback to it.
In your fallback page (or any page), you will want this (beforeMount is the important part here):
beforeMount: function () {
var host = window.location.host
this.subdomain = host.split('.')[0]
if (this.subdomain === 'www') subdomain = host.split('.')[1]
this.fetchSiteContent()
},
methods: {
fetchSiteContent() {
if (!this.subdomain || this.subdomain === 'www') {
this.siteContentLoaded = true
this.errorLoadingSite = true
return
}
// send subdomain to the server and get back configuration object
http.get('/Site/LoadSite', { params: { site: this.subdomain } }).then((result) => {
if (result && result.data && result.data.success == true) {
this.siteContent = result.data.content
} else {
this.errorLoadingSite = true
}
this.siteContentLoaded = true
}).catch((err) => {
console.log("Error loading " + this.subdomain + "'s site", err)
this.errorLoadingSite = true
this.siteContentLoaded = false
})
},
}
I store a configuration object in json in the database for the subdomain, and return that to the client side for a matching subdomain then update the site to match the information/options in the config object.
Here is my router.vue
These domain names are supported:
mysite.com (loads main/home routes)
portal.mysite.com (loads routes specific to the portal)
x.mysite.com (loads routes that support dynamic subdomain, fetches config from server)
y.mysite.com (loads routes that support dynamic subdomain, fetches config from server)
localhost:5000 (loads main/home routes)
portal.localhost:5000 (loads routes specific to the portal)
x.localhost:5000 (loads routes that support dynamic subdomain, fetches config from server)
y.localhost:5000 (loads routes that support dynamic subdomain, fetches config from server)
import Vue from 'vue'
import VueRouter from 'vue-router'
// 3 different routes objects in routes.vue
import { portalRoutes, homeRoutes, hostedSiteRoutes } from './routes'
Vue.use(VueRouter);
function getRoutes() {
let routes;
var host = window.location.host
var subdomain = host.split('.')[0]
if (subdomain === 'www') subdomain = host.split('.')[1]
console.log("Subdomain: ", subdomain)
// check for localhost to work in dev environment
// another viable alternative is to override /etc/hosts
if (subdomain === 'mysite' || subdomain.includes('localhost')) {
routes = homeRoutes
} else if (subdomain === 'portal') {
routes = portalRoutes
} else {
routes = hostedSiteRoutes
}
return routes;
}
let router = new VueRouter({
mode: 'history',
routes: getRoutes()
})
export default router
As you can see I have 3 different set of routes, one of which is a set of routes that supports dynamic subdomains. I send a GET request to the server once i load the dynamic subdomain page and fetch a configuration object that tells the front end what that site should look like.

How to handle large number of redirects in Node/Vue app?

I am working on migrating an existing app to a new tech stack that uses Node and MongoDB on the backend and Vue on the frontend. I have a fairly large number of pages that will need to be redirected to new URLs (over 50). I know I can do something like this in the frontend:
const appRouter = new Router({
mode: 'history',
routes: [
{ path: '/a', redirect: '/a2' },
{ path: '/b', redirect: '/b2' },
{ path: '/c', redirect: '/c2' },
]
});
However it doesn't strike me as particularly elegant. I could see keeping the redirects in another file and importing them to keep my router file neater, but that seems like just a formatting benefit.
I'm wondering how other people handle a large number of redirects in Vue? Would this be better to do at the server-level with Node?
If boilerplate is the problem, you can use something like:
const router = new VueRouter({
routes: [
{ path: '/([abc])', redirect: to => {
returect to.path + '2'; // to.path will be like '/a'
}}
]
})
Notice that the part inside () is a regex that can be customized.
I have a fairly large number of pages that will need to be redirected to new URLs
When we talk about redirecting a Uniform Resource Locator (URL) in the context of a Single Page Application (SPA) like Vue with Vue Router, hosted by a web server like Node.js, we might mean one of two things:
we've changed the route of a view within our Vue SPA
we've changed the location of our SPA (the resource) from one location to another.
To determine which kind of redirect you need to do, we can examine how the URL will change. URLs are made up of these components:
scheme:[//[user[:password]#]host[:port]][/path][?query][#fragment]
By default, Vue Router uses the #fragment (hash) portion of the URL to change views, so if this changes then we should redirect using Alias or Redirect.
If any other portion of the URL changes, we should have Node.js return an HTTP status code for redirect, like 301 Moved Permanently or 302 Moved Temporarily.
Normally the solution from #acdcjunior is good enough, but sometimes you may prefer hooking beforeRouteUpdate to implement the redirect.
You can check vue-router: dynamic Routing for more details.
Below is one simple sample is from the official document:
const User = {
template: '...',
beforeRouteUpdate (to, from, next) {
if ( to.match(new RegExp('your_regex_expression'))) {
next('redirect_url')
} else {
// default
next()
}
}
}
Or in main.js by using global guards:
import router from './router'
router.beforeEach((to, from, next) => {
if ( to.match(new RegExp('your_regex_expression'))) {
next('redirect_url')
} else {
// default
next()
}
})

How do I serve static files using Sails.js only in development environment?

On production servers, we use nginx to serve static files for our Sails.js application, however in development environment we want Sails to serve static files for us. This will allow us to skip nginx installation and configuration on dev's machines.
How do I do this?
I'm going to show you how you could solve this using serve-static module for Node.js/Express.
1). First of all install the module for development environment: npm i -D serve-static.
2). Create serve-static directory inside of api/hooks directory.
3). Create the index.js file in the serve-static directory, created earlier.
4). Add the following content to it:
module.exports = function serveStatic (sails) {
let serveStaticHandler;
if ('production' !== sails.config.environment) {
// Only initializing the module in non-production environment.
const serveStatic = require('serve-static');
var staticFilePath = sails.config.appPath + '/.tmp/public';
serveStaticHandler = serveStatic(staticFilePath);
sails.log.info('Serving static files from: «%s»', staticFilePath);
}
// Adding middleware, make sure to enable it in your config.
sails.config.http.middleware.serveStatic = function (req, res, next) {
if (serveStaticHandler) {
serveStaticHandler.apply(serveStaticHandler, arguments);
} else {
next();
}
};
return {};
};
5). Edit config/http.js file and add the previously defined middleware:
module.exports.http = {
middleware: {
order: [
'serveStatic',
// ...
]
}
};
6). Restart/run your application, e.g. node ./app.js and try to fetch one of static files. It should work.

Using grunt server, how can I redirect all requests to root url?

I am building my first Angular.js application and I'm using Yeoman.
Yeoman uses Grunt to allow you to run a node.js connect server with the command 'grunt server'.
I'm running my angular application in html5 mode. According to the angular docs, this requires a modification of the server to redirect all requests to the root of the application (index.html), since angular apps are single page ajax applications.
"Using [html5] mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)"
The problem that I'm trying to solve is detailed in this question.
How can I modify my grunt server to redirect all page requests to the index.html page?
First, using your command line, navigate to your directory with your gruntfile.
Type this in the CLI:
npm install --save-dev connect-modrewrite
At the top of your grunt file put this:
var modRewrite = require('connect-modrewrite');
Now the next part, you only want to add modRewrite into your connect:
modRewrite(['!\\.html|\\.js|\\.svg|\\.css|\\.png$ /index.html [L]']),
Here is a example of what my "connect" looks like inside my Gruntfile.js. You don't need to worry about my lrSnippet and my ssIncludes. The main thing you need is to just get the modRewrite in.
connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: '0.0.0.0',
},
livereload: {
options: {
middleware: function (connect) {
return [
modRewrite(['!\\.html|\\.js|\\.svg|\\.css|\\.png$ /index.html [L]']),
lrSnippet,
ssInclude(yeomanConfig.app),
mountFolder(connect, '.tmp'),
mountFolder(connect, yeomanConfig.app)
];
}
}
},
test: {
options: {
middleware: function (connect) {
return [
mountFolder(connect, '.tmp'),
mountFolder(connect, 'test')
];
}
}
},
dist: {
options: {
middleware: function (connect) {
return [
mountFolder(connect, yeomanConfig.dist)
];
}
}
}
},
FYI Yeoman/Grunt recently changed the default template for new Gruntfiles.
Copying the default middlewares logic worked for me:
middleware: function (connect, options) {
var middlewares = [];
var directory = options.directory || options.base[options.base.length - 1];
// enable Angular's HTML5 mode
middlewares.push(modRewrite(['!\\.html|\\.js|\\.svg|\\.css|\\.png$ /index.html [L]']));
if (!Array.isArray(options.base)) {
options.base = [options.base];
}
options.base.forEach(function(base) {
// Serve static files.
middlewares.push(connect.static(base));
});
// Make directory browse-able.
middlewares.push(connect.directory(directory));
return middlewares;
}
UPDATE: As of grunt-contrib-connect 0.9.0, injecting middlewares into the connect server is much easier:
module.exports = function (grunt) {
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
grunt.initConfig({
// The actual grunt server settings
connect: {
livereload: {
options: {
/* Support `$locationProvider.html5Mode(true);`
* Requires grunt 0.9.0 or higher
* Otherwise you will see this error:
* Running "connect:livereload" (connect) task
* Warning: Cannot call method 'push' of undefined Use --force to continue.
*/
middleware: function(connect, options, middlewares) {
var modRewrite = require('connect-modrewrite');
// enable Angular's HTML5 mode
middlewares.unshift(modRewrite(['!\\.html|\\.js|\\.svg|\\.css|\\.png$ /index.html [L]']));
return middlewares;
}
}
}
}
});
}
There is a pull request I sent for this problem: https://github.com/yeoman/generator-angular/pull/132, but you need to apply it manually.
To deeply simplify #Zuriel's answer, here's what I found to work on my behalf.
Install connect-modrewrite: npm install connect-modrewrite --save
Include it in your grunt file: var rewrite = require( "connect-modrewrite" );
Modify your connect options to use the rewrite:
connect: {
options: {
middleware: function ( connect, options, middlewares ) {
var rules = [
"!\\.html|\\.js|\\.css|\\.svg|\\.jp(e?)g|\\.png|\\.gif$ /index.html"
];
middlewares.unshift( rewrite( rules ) );
return middlewares;
}
},
server: {
options: {
port: 9000,
base: "path/to/base"
}
}
}
Simplified this as much as possible. Because you have access to the middlewares provided by connect, it's easy to set the rewrite to the first priority response. I know it's been a while since the question has been asked, but this is one of the top results of google searching regarding the problem.
Idea came from source code: https://github.com/gruntjs/grunt-contrib-connect/blob/master/Gruntfile.js#L126-L139
Rules string from: http://danburzo.ro/grunt/chapters/server/
I tried all of these, but had no luck. I am writing an angular2 app, and the solution came from grunt-connect pushstate.
All I did was:
npm install grunt-connect-pushstate --save
and in the grunt file:
var pushState = require('grunt-connect-pushstate/lib/utils').pushState;
middleware: function (connect, options) {
return [
// Rewrite requests to root so they may be handled by router
pushState(),
// Serve static files
connect.static(options.base)
];
}
and it all worked like magic.
https://www.npmjs.com/package/grunt-connect-pushstate

Flatiron js - director - how to do async routing from a table?

I'm starting to get things set up using flatiron as the toolset for a web app.
I'm using director with app.plugins.http, and can't seem to figure out how to create a "catchall" route for static files & 404s - It appears that .get("<RegEx>") only matches the first folder position, so if <RegEx> is /.*, it'll match /foo, but not /foo/bar.
Here's my code, as a better example:
in routes.js:
var routes = {
/* home
* This is the main route, hit by queries to "/"
*/
"/" : {
get: function(){
getStatic("html/index.html",_.bind(function(err,content){
if(err) throw err;
renderContent(this,content);
},this));
}
},
/* static files
* Last rule, if no other routes are hit, it's either a static resource
* or a 404. Check for the file then return 404 if it doesn't exist.
*/
'/(.*)' : {
get : function(){
getStatic(this.req.url,_.bind(function(err,content){
if(!err){
renderContent(this,content);
} else {
this.res.writeHead(404);
// TODO: fancier 404 page (blank currently)
this.res.end();
}
},this))
}
}
}
and in my main app file:
/* Define the routes this app will respond to. */
var routes = require('./lib/routes');
/* set up app to use the flatiron http plugin */
app.use(flatiron.plugins.http);
/* loop through routes and add ad-hoc routes for each one */
for(var r in routes){
var route = routes[r];
if(!routes.hasOwnProperty(r)) continue;
for(var method in route){
if(!route.hasOwnProperty(method)) continue;
app.router[method](r,route[method]);
}
}
/* Start the server */
app.listen(8080);
I'd like to be able to keep my routes in a separate module and import them - I'm pretty unclear on if this method or using director and a vanilla http server would be better, but I've tried both ways without any luck.
Here's what I get:
localhost:8080/
>> (content of index file - this works)
localhost:8080/foo
>> (blank page, 404 header)
localhost:8080/foo/bar
>> (no static file for this - I get a 404 header, but the body is now "undefined" - where is this coming from??)
localhost:8080/css/min.css
>> (this file should exist, but the route is never called. I do however still get a 404 header, and get the "undefined" body)
so, I'm assuming the "undefined" body is default behavior for undefined routes.
Is there a way to create a catchall route without adding rules for each depth?
You could try using node-ecstatic which is a static file serving add-on for flatiron. It works well for me and you can find it at:
https://github.com/colinf/node-ecstatic
Try using onError:
app.use(flatiron.plugins.http,{
onError: function (err) {
this.res.end('Nope');
}
});
To manage your static files I suggest you to use flatiron/union + connect.static

Resources