Backend Packages & Serve - Vincentvanleeuwen/project-tech-2020 GitHub Wiki
Packages
Every Node project has a package.json file. In this package.json file you can add all kinds of packages. Packages are actually bundles of pre-written pieces of code. You have packages like nodemon, that check all your files for changes and then restart the app so you automatically see the new changes. This is what they call a Dev-Dependency. It's called a dev-dependency because you can use certain packages for just developping. Once you move your app to production, these packages will not be required anymore.
Then you also have the normal Dependencies. Here you can find packages like, Express.js, MongoDB (for databases), and templating engines like EJS or Handlebars.
You can install these packages either globally or locally. The difference is that if you install it globally and someone else downloads the project, he won't be able to run npm install because all the packages are only globally installed. (unless he defined the packages within the package.json).
You can also set custom scripts in your package.json. You can for instance set the script dev to nodemon server.js. Once you then run npm run dev in your terminal, it'll actually run nodemon server.js. This saves you a little bit of typing time!
Serve
Now that the package.json is installed correctly you can start the server by running node app.js (or npm run dev if you've defined your scripts).
You can define all the routes you're going to need by using app.get('/[ROUTE]). Express will then create this new route, and send the data you've placed with it. Once defined you can use res.send() to send the new page to the view, and run the server by using app.listen.
There's also app.post('[ROUTE]'), when you create a form with the method post, it'll send the data with it to that route. Be sure to have bodyParser installed so you can call req.body on the form to get the data out of it.
Sources
"4.x Api", Expressjs, https://expressjs.com/en/api.html, at date 3 June. 2020,
Wanyoike, M., and Dierx, P.“A Beginner's Guide to Npm, the Node Package Manager.” SitePoint, 3 Mar. 2020, www.sitepoint.com/beginners-guide-node-package-manager/. at date 3 June. 2020,