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.
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:
// back/src/app.jsimportexpressfrom'express'importcookieParserfrom'cookie-parser'// parses cookiesimportsessionfrom'express-session'// parses sessionsimportfaviconfrom'serve-favicon'// serves faviconimportcorsfrom'cors'// allows cross-domain requestsimportcreateErrorfrom'http-errors'// better JS errorsimportpathfrom'path'constapp=express();// create a new appconstIS_PRODUCTION=app.get('env') ==='production'if (IS_PRODUCTION) {app.set('trust proxy',1) // secures the app if it is running behind Nginx/Apache/similar}app.use(cors()) // allows cross domain requestsapp.use(express.json());// allows POST requests with JSONapp.use(express.urlencoded({extended:false}));// allows POST requests with GET-like parametersapp.use(cookieParser());// Parses cookiesapp.use(favicon(path.join(__dirname,'../public','favicon.ico'))) // <-- location of your faviconapp.use(express.static(path.join(__dirname,'../public')));// <-- location of your public dirapp.use(session({// handles sessionssecret:'keyboard cat',// <-- this should be a secret phrasecookie:{secure:IS_PRODUCTION},// <-- secure only in productionresave:true,saveUninitialized:true}))exportdefaultapp
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.