Express
To handle requests, we could use the native http
module, but it can get cumbersome to read the url, to determine different routes, to check which http verb was used, and so on. A bit of help doesn't hurt. There, too, we have a lot of contenders (Fastify, Restify, Koa, Polka, Restana, ...). Two main ones are Hapi and Express.
For popularity reasons, we're going to go with Express.
However, express on its own lacks a few capabilities. Namely, it doesn't handle POST requests, nor file uploads. It also doesn't handle sessions, and won't allow requests from another domain unless we tell it to.
Move to the back
directory, and then:
express-session
: Lets Express handle sessionscookie-parser
: Lets Express parse cookies sent by the browserserve-favicon
: automates serving a faviconcors
: Allows us to specify easily that Express should answer requests, even if from another domainmulter
: Lets Express read file uploadshttp-errors
: Allows us to create relevant Javascript errors in a slightly easier way
Once everything is installed, we'll use Express in index.js
.
Create a file src/app.js
, in which we'll set up everything:
You notice we haven't used multer
, the file upload plugin. That's because we will want to use it on a per-route level. You will need to create a directory public
next to src
, and store in it favicon.ico
. You can download a favicon here or get the codi favicon from there. If you use a png, don't forget to change the path in your application.
Let's import this file in index.js
, and use it instead of the http
module:
We can test that everything works by running npm start
, or, from the root, npm run back
.
Last updated
Was this helpful?