Express
Last updated
Was this helpful?
Last updated
Was this helpful?
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 (, , , , , ...). Two main ones are and .
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 sessions
cookie-parser
: Lets Express parse cookies sent by the browser
serve-favicon
: automates serving a favicon
cors
: Allows us to specify easily that Express should answer requests, even if from another domain
multer
: Lets Express read file uploads
http-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:
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
.
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 or get the codi favicon from . If you use a png, don't forget to change the path in your application.