Writing your first complete express server!
Writing your first complete express server!
Daniel Roizer
Writing down a server can be hard in some orthodox environments, but express.js comes with the proposal for easily building a robust and fast API. Providing to you a lot of HTTP methods and features for web and mobile applications.
A little bit of motivation and advantages on using express:
- Easy to set and run.
- Large community, a lot of help and examples across the web. It is the most popular Node.js framework.
- Takes advantage of JavaScript features like closures.
- You can make use of exports and require features for modularization.
- Good and easy integrations. Connect and build a database with MongoDB, Redis or other database frameworks, for example.
Let’s have some flavours on express now.
Note: The entire code of this post is available here.
Markus Spiske
Make sure you have already installed Node.js and let’s start creating our app folder now. Use npm init command to create a the package.json file. This file handles the app configuration and dependencies, feel free to write it as you want.
$ mkdir server
$ cd server
$ npm init
Note: Pay attention when typing the entry point name, a file with the chosen name should be in the application folder. By default the framework will look for the entry point file to run the application.
Finally install the express dependency with the save flag which guarantees that express is saved to your list of dependencies on package.json.
$ npm install express --save
energe.pic
You should start your simple server writing in our entry point, index.js
, file the lines below. The code below requires from node the express module, initializes the express app and sets it to listen on port 3000.
const express = require("express");
const app = express();app.listen(3000, function () {
console.log("App listening on port 3000!");
});
To run the app you should do the following command on terminal:
$ node .
Hint: You are able to set a start script configuration in your package.json by adding a new script in the scripts tag like:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node ."
},
Right now you can run the server using the shortcut npm start
. It is possible to write some scripts to make your life easier, but let’s move forward on express.
After running your server using your favourite command you will have the server running and listening on port 3000. However, if you try to access your application running http://localhost:3000 in your browser you will get an error: Cannot GET/
.
Ilya Pavlov
The error occurred because there is no handler assigned to a GET on /
path. We can provide a handler writing down some simple code:
app.get("/", function (req, res) {
res.send("Hey, I am responding to your request!");
});
The snippet above assigns a function to the /
path when the app receives a GET request. The res
contains features and properties for you to deal with the response and answers the request using the send method sending a message. The req
is not used in this example, but it handles the request information.
If you restart your server now and go for http://localhost:3000 you will get the message that we wrote.
Skippable Pro Hint – Server restart automatically: Every time you make any change to your server code the app needs to be relaunched by the terminal. Fortunately we have Nodemon for that; a utility that will monitor any changes in your source and automatically restart your server. Install using npm:
$ npm install nodemon --save
And change your start script to:
"scripts": {
"start": "nodemon ."
},
That makes your developing experience smoother and faster. =)
So let’s go back to GET/POST methods. To handle requests with your express app you should use the format app.METHOD(PATH, HANDLER)
.
- The METHOD can be [get, post, put, delete, …].
- The PATH is the actual path you are handling.
- The HANDLER is the function that runs when you perform this type of request to this path.
Take a look at the API documentation for more.
Your answer to a request is flexible and can be, for example, an object or HTML content too. Try out the following code:
app.get("/home", function (req, res) {
res.send("<h1>I am a header.</h1>");
});
If you access http://localhost:3000/home you will see the text formatted as a header.
You are also able to define routes with parameters. The parameters are available to read from req.params
. Try out the example below where we define the object teams and the path for getting a team.
const teams = {
1: {
name: "Sport Club do Recife",
foundation: "13/05/1905"
}
};app.get("/teams/:id", function (req, res) {
if(teams[req.params.id] !== undefined){
res.status(200).send(teams[req.params.id]);
} else {
res.status(404).send("Oops! 404: Team not found!");
}
});
Accessing http://localhost:3000/teams/1 you will receive the team object shown in the screen corresponding to the id given as parameter. What’ll happen if you go for http://localhost:3000/teams/2?
Hint: It’s always good to set the status of the response when you are answering the request. Doing that you are providing more information about the request or server. Take some time to look at the defaults HTTP status code.
Jerry Kiesewetter
Post methods are not too different, but requires others dependencies to handle parameters. When you are posting to an express.js app it happens that the req.params
does not contain the information posted. Instead of reading it from the params you will need to parse it from the request body. So first of all install body-parser
, a module that helps us to unwrap the post request content.
$ npm install body-parser --save
Require the module on your server app and set the app to use it:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
bodyParser.json()
returns a middleware that only parses json
and accepts any Unicode encoding. For understanding urlencoded
options check out the documentation.
Now you are ready to try some POST. For educational purpose I will write some HTML for my form on a variable and return it, but keep in mind that there are better ways to do it. And also, you are able to post from other application to this server.
+"Name:<br>"
+" <input type=\"text\" name=\"name\" value=\"\">"
+" <br>"
+" Foundation:<br>"
+" <input type=\"text\" name=\"foundation\" value=\"\">"
+" <br><br>"
+" <input type=\"submit\" value=\"Submit\">"
+"</form>";const form = "
http://localhost:3000/addTeam\ ">"+"Name:
"+" "+"
"+" Foundation:
"+" "+"
"+" "+"";app.get("/addTeam", function (req, res) {
res.status(200).send(form);
});app.post("/addTeam", function (req, res) {
res.status(200).send("You have posted a team of name: "+req.body.name+" and foundation: "+req.body.foundation);
});
When accessing http://localhost:3000/addTeam the express knows you are doing a GET and presents you a page with a simple form to submit a team data. Submitting the data in the form implies to do a POST to the action url.
The express handles the form submission and thanks to the body-parser
we can access the data through the req.body
property and work with it. Note that you access the data through the name given in the input tag on HTML.
Congratulations! Now you have enough power to build an app/server which responds to GET/POST requests and do whatever job you want. You are now able to explore some data storage, processing, routing, etc.
It may be sufficient for doing all the job you want now, but I encourage you to take a break, play with what you have just learned and come back here to look at the next topics. However they are not always needed, they can be very useful in your further applications.
Jeffrey Betts
A resource makes a cross-origin HTTP request when it requests a resource from a different domain or port from the one which the first resource itself serves. Cross-origin resource sharing (CORS) is a mechanism that allows those requests to happen. Modern browsers restrict cross-origin HTTP requests initiated from within scripts.
So, if you are writing an application that requests some resource using XMLHttpRequest or Fetch then you should know that these APIs only make HTTP requests to its own domain. For example, if you request from another application (hosted in other domain or port) the teams of our server, the browser will prevent it to load. Application will fail on loading the resource unless we allow our server to deal with CORS.
Enabling CORS is actually very simple. Express has it own module for CORS and you can install it through npm.
$ npm install cors --save
Require the module in the server and set the express app to use it.
[...]
const cors = require("cors");
const app = express();app.use(cors());
[...]
Right now the CORS are enabled for all origins and in all routes, but if you already know from which domains it could accept a cors request you should restrict to those domains through a whiteList.
var whiteList = [" http://localhost:8000 ", " http://localhost:3000 ", " http://localhost:8080 "];
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (whiteList.indexOf(req.header("Origin")) !== -1) {
corsOptions = { origin: true };
} else {
corsOptions = { origin: false };
}
callback(null, corsOptions);
}app.use(cors(corsOptionsDelegate));
Only requests coming from those listed domains are able to proceed. In addition to that, you may set the cors only for specific routes. This is done by adding the cors as a parameter of the method function. For example:
app.get("/", cors(), function (req, res, next) {
res.status(200).send("CORS enabled for this route.");
})
And that’s all for handling CORS. Your application is even more robust now!
Ej Agumbay
Sessions are normally associated with authentication when this involves the process verifying whether a user is who he declares to be or not, as well as if he/she has the privileges to access the requested resources. So if you need authentication or privileges on your app take a look into the next steps.
The two main ways of working on authentication is using cookies
or using sessions
. Both approaches have a middleware and modules on express. In this tutorial I will work with express-session
. By now you should have used to installing and saving the dependencies.
$ npm install express-session --save
You may now require the module in your app and set the express to use it.
const session = require("express-session");
app.use(session({
secret: "YOUR$UP3R$3CR3T",
resave: true,
saveUninitialized: true
}));
Plenty of other options on session and cookies are allowed to configure your session manager. For example, you may want to set a time limit for the session’s life, it can be done through the cookie.maxAge
property. Look at Documentation for more options and details. For this example we just used a few of them and they are:
secret
is required and is the secret used to sign the session ID cookie.resave
is true so it forces the session to be saved back to the session store, even if the session was never modified during the request.saveUninitialized
is true so it forces a session that is “uninitialized” to be saved to the store. A session is uninitialized when it is new but not modified.
You now have a session set and you can work on your app authentication process. Every req
object now has a session
property so you can retrieve the session id of the request as well as you can set new properties to one session. You can save, for example, the email of the authenticated user as session.email = [email protected]
and you can make every request look at the email of the session to know; if the user is logged, who he/she is and what he can do.
Warning: The default server-side session storage, MemoryStore, is purposely not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is meant for debugging and developing.
The quote above is from express-session
documentation and it makes clear that the default session storage is meant for developing and debugging, but not for production. Luckily, express-session
allows easy integrations with other types of storage like RedisStore or MongoStore so you may want to check out the Compatible Sessions Stores.
Feel free to explore more on sessions and implementing your authentication system!
Summing up
Express.js is a powerful and light framework that runs over Node.js. Easy to configure and implement, it allows you to write fast handlers for HTTP requests, provides you CORS compatibility, Sessions handler modules and others. In addition to ease integrations with other frameworks such as database APIs.
I hope it has been a good and useful tutorial on giving you the first steps in express! Explore, implement and share your progress to the community!
Comments and suggestions are welcome. o/