In this section we will start up a new express project! ✨
You can download the end product from my github! Click here!
1) Start up Express Project (manual)
# Create a folder
mkrdir <folder-name-here>
# initialize npm
# keep clicking enter and select Yes at the end
npm init
# install express
npm i express
# install nodemon
# '-g' means global download, ie you only need to do it once and from here on - all your projects will have nodemon
npm i nodemon -g
# create a server.js / index.js file (it's just naming)
touch server.js
if you installed nodemon you would need to update your package.json!
this is so that when you run npm run start
it would automatically use nodemon
package.json
{
"name": "mongoose-tutorial",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon server.js", // add this line here! ✨
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.19.2"
}
}
2) add in boilerplate code for express
server.js
// Load express
const express = require('express');
// Create our express app
const app = express();
// Define a "root" route directly on app
// this is usually to test that my end points on my server is actually running
app.get('/', function (req, res) {
res.send('<h1>Hello World!</h1>');
});
app.get('/booking', function (req, res) {
res.send('Here is all your bookings!');
});
app.post('/booking', function (req, res) {
res.send('Thanks for the new booking!');
});
app.patch('/booking', function (req, res) {
res.send('You have updated your booking partially!');
});
app.put('/booking', function (req, res) {
res.send('You have updated the your booking entirely!');
});
app.delete('/booking', function (req, res) {
res.send('You have deleted the booking!');
});
// Tell the app to listen on port 3000
// for HTTP requests from clients
app.listen(3000, function () {
console.log('Listening on port 3000');
});
3) run the app
# node server.js
nodemon server.js
Let's Learn!
What does app.xxx()
do?
app.get('/booking', function (req, res) {
res.send('Here is all your bookings!');
});
app.post('/booking', function (req, res) {
res.send('Thanks for the new booking!');
});
app.patch('/booking', function (req, res) {
res.send('You have updated your booking partially!');
});
app.put('/booking', function (req, res) {
res.send('You have updated the your booking entirely!');
});
app.delete('/booking', function (req, res) {
res.send('You have deleted the booking!');
});
These code define how your express application responds to GET / POST / PATCH / DELETE requests to specific path.