Hướng dẫn nodejs get full url
In 2021 The above answers are working fine but not preferred by the Documentation because Express WayYou can get
Example URL: http://localhost:5000/a/b/c?d=true&e=true#f=false Fixed Properties ( you will get the same results in all routes )
Not Fixed Properties ( will change in every route because it controlled by express itself ) Route:
Route
Documentation: http://expressjs.com/en/api.html#req.baseUrl URL Package WayIn the Properties
You will get the results like the below. I changed the order of the properties as per the image so it can match the image flow.
Note: Documentation: https://nodejs.org/api/url.html#url_new_url_input_base URL stands for Uniform Resource Locator. It is used to locate some resources on the internet it can be thought of as a web address. The string you type on your browser search bar to get something from the internet is a URL, so in this process, the browser somehow finds the address of the server associated with that web address and says hey, this is the content(an URL) I have got from the user and now tell me how I should respond. Now it is the server’s responsibility to respond according to that request. And after receiving a response, it’s the browser’s responsibility to provide that received data to a user in the way it is expected. Problem statement: So that was pretty much about URL, now our problem statement is how to get that URL at the server? Because during the application in production, several times we need the Whole components of URL to understand the user requirements so that later server can fulfill them by sending a proper response. Approach: There is an easy and simple approach to solve this because directly or indirectly the user sends the request object and it contains sufficient information for the server. And we can extract essential properties from that object according to our needs. In this article, at step number 4, we are going to discuss how to construct the URL from this request object sent by the user. Step 1: Creating nodejs project and installing packages. 1. Create a nodejs application. As the whole operation is going to proceed with express framework hence it is the first compulsory step to create a node application. npm init 2. This will ask you for few configurations about your project you can fill them accordingly, also you can change it later from the package.json file, you can use `npm init -y` for default initialization. Install express framework npm install express 3. Create a new file app.js, inside this file, we will write the whole express code. Project Structure: It will look like the following. Step 2: Creating an express application. So inside app.js do the following:
The callback function provided as an argument gets executed either on the successful start of the server or it provides an error due to failure. app.js |