How to set a base URL for NodeJs applications using ExpressJs server and AngularJs for frontend?

I want to add a base URL to my application when I load it on my browser.

My expressJs config is:

App.js

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressSanitizer());
app.use(express.static(__dirname + '/webapp'));
app.engine('html',require('ejs').renderFile);
app.set('view engine', 'html');

AngularJs router config:

index.js

$urlRouterProvider
        .when('','login')
        .when('/','login')
        .otherwise(function($injector, $location){
            var state= $injector.get('$state');
            state.go('error', { url: $location.path() }, { location: true });
        });

        //define states
        $stateProvider
        .state('/',{
            templateUrl: 'public/login.html',
            controller: 'login',
            authenticated:false
        })
        .state('login',{
            url: '/login',
            templateUrl: 'public/login.html',
            authenticated:false
            // controller: 'login'
            // template: '<h1> Routing to login page </h1>'
        })

I want it similar to that when we deploy application in Apache Tomcat.

Currently when I start the server the url is like localhost:8080/login but I want it as localhost:8080/CRM/login

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

So, I figured out the solution in this way.

I added a base tag in my index.html and added ‘/CRM’ in all my api’s in my App.js

index.html

<base href="/CRM/" rel="nofollow noreferrer noopener">

App.js

app.use('/CRM/users',appRoutes);

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply