Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the better way to identify the context path in Angular JS

I have my web application deployed to tomcat with an applicatio context. For example my URL looks something like this.

http://localhost:8080/myapp

myapp - is the application context here.

Now in an Angular service if i want to call a webservice say getusers. My URL should be this /myapp/getusers. But I want to avoid hardcoding the application context as it might change from one deployment to other. I have managed to figureout the contextpath from $window.location.pathname but it looks very stupid. Is there a betterway?

FYI I am using Spring MVC for restful services.

like image 414
darwinbaisa Avatar asked Jun 10 '13 10:06

darwinbaisa


People also ask

How do I find context path?

The typical way of getting the context path is through the HttpServletRequest class. Simply you can add a HttpServletRequest parameter to your controller method and then get the context path using getContextPath() method. Now that you get the context path, you can pass it to the services that need it.

What is context path in Javascript?

The context path is the prefix of a URL path that is used to select the context(s) to which an incoming request is passed. Context path is also known as sub-path or sub-directory. Many apps are hosted at something other than the root (/) of their domain.

What is URL context path?

The context path of a web application defines the URL that end users will access the application from. A simple context path like myapp means the web app can be accessed from a URL like http://localhost:8080/myapp.

What is$ location in AngularJS?

The $location in AngularJS basically uses a window. location service. The $location is used to read or change the URL in the browser and it is used to reflect that URL on our page. Any change made in the URL is stored in the $location service in AngularJS.


2 Answers

I'm also using tomcat and Spring MVC. Using relative url in JavaScript will do the trick.

For doing this you just need to remove the / at the begining of REST url. so that your url starts from the current url in your browser.

replace $resource('/getusers') with $resource('getusers')

like image 102
Qianlong Avatar answered Sep 21 '22 03:09

Qianlong


For AngularJS $http service you are good to go with url : 'getusers', as follows:

$scope.postCall = function(obj) {
            $http({
                method : 'POST',
                url : 'getusers',
                dataType : 'json',
                headers : {
                    'Content-Type' : 'application/json'
                },
                data : obj,
            });
};
like image 44
Arpit Aggarwal Avatar answered Sep 17 '22 03:09

Arpit Aggarwal