Coming from Java world, where the Servlet-based application context path is set based on the WAR file name, I am trying to understand the best practices for defining context path in Node.js.
The Node application in question has no context path defined in the code. The Express code assumes that request to get a story, for example, has URL with path of /story/1. Thus, JavaScript UI code would makes a request to http://host:port/story/1. Likewise, for the user to connect to the main app page, they would go to http://host:port/.
I would like to change the URL the user sees to http://host:port/myapp. The question is how to consistently define "myapp" as the application context. The options I am considering:
How do I make sure that the user always sees "myapp" in the URL? Do I also need to remap all the internal requests (the ones made by the UI code) to also have '/myapp' context?
Using Nginx seems cleaner since it does not require changing the code. But can this objective be achieved through Nginx configuration alone and if so, how?
Since this is a common problem, there must be a well-defined pattern for solving it.
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.
1- HttpServletRequest 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.
The context path is the name of the URL at which we access the application. The default context path is empty. The context path can be changed in many ways. We can set it in the properties file, with the SERVER_SERVLET_CONTEXT_PATH environment variable, with Java System property, or on the command line.
A context root identifies a Web application archive (WAR) file in an application server. The context root of a Web application determines which URLs application server will delegate to your web application. When MobileFabric installed, the required components' WARs are deployed to an app server.
As you said it's better to do it in nginx config for the sake of context path independence from application code.
On the nginx side, you can set the context path with location
directive and then you can remove the context path
from path and send the request to the application. It can be done with a rewrite directive of nginx as follows:
location /myapp/ {
rewrite ^/myapp/(.*)$ /$1 break;
...
}
Thus, in nodejs (express) side You should suppose that the application is running under the root path (/) as you said.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With