Creating a Server with Express
What Express JS?
Express.js is a really neat and highly adopted framework for Node.js that makes it trivial to build an API. It's by far the most popular one due to it being created near Node.js' time of creation and how much support the community has poured into it. Express is synonymous with Django for Python, Sinatra for Ruby, Spring for Java, and Gin for Go Lang
So it's basically just a really cool framework that the Node community has adopted as it's go to, it's definitely by far the most popular one.
It was built on something called Connect that's no longer alive.
But at the time, it basically came out around the time that Node.js did, so it was just the de facto framework for building API's with Node.js.
It's literally the same thing.I mean, they all do something very differently but that's basically what it is.And like I said earlier,there are other frameworks out there they are faster, newer, better, but at the end of the day everyone respects Express, it's not going anywhere.
Dependencies
Before we can use Express, we need to install it. Using NPM or Yarn:
npm i express --save
Next, let's create a simple API!
- We have change the
type:'module'
inpackage.json
file. for using ES6 module syntax. - adding new scripts in the
package.json
file for running the server we used thenodemon
package for auto-reloading the server. - nodemon is npm package that i have globally installed on the system.
"start": "nodemon index.js",
- server.js
- index.js
- Response
import express from "express";
const app = express();
app.get("/", (req, res) => {
res.status(200).send({
success: true,
message: "Welcome to the Node.js and Express API",
});
});
export default app;
import app from "./server.js";
app.listen(3001, () => {
console.log("Server is running on http://localhost:3000");
});
{
"success": true,
"message": "Welcome to the Node.js and Express API"
}
- A server can send back, I mean,think of anything you have ever seen on a website before or a mobile app ora video game, a server can send that back.
- So there has no limit to, if it is a file, it can be sent.If it is data, it can be sent.There is no limit to it.It just depends on what the client does with that information.
Express literally gives us a framework to build out the business logic of our APIs without having to put too much thought into how to make the API functional in the first place.