Going Express with Node.js [Part #1]

Developing server-side applications with Express.js

# The Beginning

# Setting Up the Basics

Figure 01 — Suggested folder structure.
Source: https://giphy.com/
$ npm init -y
$ npm i --save express

# The Bare Minimum For an Express Web Server

// step 01: require the express module.
const express = require(“express”);
//step 02: create a variable to access all the express funcitonalities.
const app = express();
app.get(“/”, (req, res) => {
res.status(200).send(“Hello Express!”);
});
// step 03: declare the port and call the listener to start the server.
const PORT = process.env.PORT || 8080;
app.listen(PORT, (req, res) => {
console.log(`Server up and running on port ${PORT}`);
});
$ node src/index.js
Figure 02 — Message returned by the Express web server.
Figure 03 — Console log message displayed.

# Managing Routes and Handling Requests

app.method(path,handler)

## Implementing The User Route

// step 01: require the express module.
const express = require("express");
// step 02: create a variable to instantiate the Router.
const router = express.Router();
router.get("/", (req, res) => {
res.status(200).send(`Welcome to the /user path in the user route`);
});
// step 03: export the router.
module.exports = router;
// step 04: call the router setting up the route:
app.use("/user", require("./routes/user"));
// step 01: require the express module.
const express = require(“express”);
//step 02: create a variable to access all the express funcitonalities.
const app = express();
// step 04: call the router setting up the route:
app.use("/user", require("./routes/user"));
app.get(“/”, (req, res) => {
res.status(200).send(“Hello Express!”);
});
// step 03: declare the port and call the listener to start the server.
const PORT = process.env.PORT || 8080;
app.listen(PORT, (req, res) => {
console.log(`Server up and running on port ${PORT}`);
});
Figure 04 — Message displayed by the browser when the user tries to access the “/user” route.

# Conclusion

# References

Engineer | Fullstack Developer | Roboticist | Freelance Writer