Written by
Jan Kaiponen
on
on
Express JS Crash Course
Started to watch the video again. This time working through the examples.
Basic Server Syntax
const express = require('express);
// init express
const app = express();
// create your endpoints / route handlers
app.get('/', function (req, res) {
// fetch from database...
// load pages ...
// return JSON ...
// full access to request & response
res.send('Hello World!');
});
// listen on a port
app.listen(5000);
Handling requests
- app.get()
- app.post()
- app.put()
- app.delete()
Access to params, query strings, url parts, etc
Express has a router; we can store routes in separate files and export
Can parse incoming data with the body parser
Middleware
Functions that have access to the request and response object.
“A stack of functions that executes when a request is made to the server”
- Execute any code
- Make changes to the request/response objects
- End response cycle
- Call next middleware in the stack
Creating a new app
npm init -y
npm i express
Main entry point to the app
index.js
dotenv
- Use dotenv for configuration management (REST api tutorial)
const express = require('express')
const app = express();
require('dotenv').config()
.env
KEY=VALUE
nodemon
This will watch source files and restart the server when needed.
npm i --save-dev nodemon
package.json
"scripts": {
"devStart": "nodemon server.js"
},
npm run devStart