How to define routes with Express?
Exploring the world of web development involves understanding the importance of paths. On any website you visit, you will notice the presence of multiple paths such as /contact
, /categories
, or /products
. These paths are essential to the organization and operation of a web application. Using Express, a popular framework for Node.js, we can easily manage and define these routes for our application.
How to create a basic route in Express?
The starting point when working with Express is to set up our routes in a clear and simple way. When you access localhost:3000
or whatever port you have configured, you are confronted with the main route, which in our case shows "Hello My Server in Express", due to the default configuration. What happens if we want to create a new route? Suppose we want to define a route called /new-route
. We can do it as follows:
app.get('/new-route', (req, res) => { res.send('Hello I am a new route');});
Adding a route like /products
is just as simple:
app.get('/products', (req, res) => { res.send('We want the products');});
How to respond with different types of formats?
In server development, it is not only the creation of routes that is important, but also the type of response we send to our users. Although we could initially respond with a simple string, the most useful and common is to do it in JSON (JavaScript Object Notation) format.
By responding with JSON, we facilitate communication with front-end or mobile applications. For example, we could define a JSON response in our /products
path as:
app.get('/products', (req, res) => { res.json({ name: 'Product 1', price: 1000 });});
This structure allows our data to be more understandable and structured, especially when handling APIs.
How to visualize JSON better?
Working with complex JSON can be a challenge if you don't use the right tools for visualization. Therefore, we recommend installing an extension to help you view JSON in an organized way. For Google Chrome users, JSON Viewer
is an excellent choice. However, if you use another browser, look for similar extensions that will optimize your experience.
Once the extension is installed, reloading pages with JSON becomes a more manageable experience, as they allow you to see details of the requests clearly.
How to practice creating routes?
The best way to learn is to practice. I challenge you to create additional routes in your application such as /categories
or /start
. Experiment with the responses, either in plain text or JSON format. Also, share in the comments how was your experience installing the JSON plugin.
Take these basics to advance your mastery of Express and continue to explore new possibilities in developing robust and efficient web applications. And remember, this is just the beginning of a fascinating journey into the world of RESTful APIs!
Want to see more contributions, questions and answers from the community?