# Express https://www.npmjs.com/package/express One of the most popular libraries to **build server** with node. :::info Ref. [The State of JavaScript Developer Survey](https://stateofjs.com/) ::: ## Install ```bash $ npm install express ``` ## Building a server with Express.js ```javascript const express = require('express'); const app = express(); app.listen(3000); ``` - `express()` - `const app = express()` - `listen()` - `app.listen(3000)` ## Do a `GET` request in Express ```javascript const express = require('express'); const app = express(); app.get('/', (request, response) => { response.send("helllloooo") }); app.listen(3000); ``` ### Basic routing ```javascript app.METHOD(PATH, HANDLER) ``` - `app` - an instance of express - `METHOD` - HTTP request method - `PATH` - path on the server - `HANDLER` - function executed when route is matched\ Content type is automatically converted: - `text/HTML` ![](https://i.imgur.com/0InxSOW.png) - `application/JSON` is also automatically converted ```javascript const express = require('express'); const res = require('express/lib/response'); const app = express(); app.get('/', (request, response) => { const user = { name: "Sally", hobby: "soccer" }; response.send(user); // don't need to use JSON.stringify() }); app.listen(3000); ``` ![](https://i.imgur.com/QEmbDMc.png) ## Express Middleware ```javascript const express = require('express'); const app = express(); app.use ( (req, res, next)=> { consol.log('<h1>hellooooo</h1>'); next(); }) ``` - `.use()` - a generic express middleware - req - res - `next()` - In order for the middleware to keep passing through, it needs to call: `next()` The way middleware works: 1. `app.use()` gets the request of the website 2. do whatever you want with it (in the case above, just console.log) 3. hit `next()` and express keeps running through the rest of the code :::info Middleware: Something that receives ahead of time before getting through the routes. ::: ### Using `body-parser` as a middleware ```javascript app.post('/profile', (req, res) => { console.log(req.body) req.send(user) }) ``` If we want to access `req.body`, we need to use a middleware: [body-parser - npm (npmjs.com)](https://www.npmjs.com/package/body-parser), it will grab anything it receives and parse it ```bash npm install body-parser ``` :::info **💡Express Version Update** If you are running a version of Express that is ***4.16+***, it now includes the same functionality inside of Express. Instead of adding these lines in the code like: 1. `app.use(bodyparser.urlencoded({extended: false}));` 2. `app.use(bodyparser.json());` If you are using **Express 4.16+** you can now replace that with: 1. `app.use(express.urlencoded({extended: false}));` 2. `app.use(express.json());` ::: ### app.use() ```javascript app.use(express.urlencoded({extended: false})); app.use(express.json()) app.post('/profile', (req, res) => { console.log(req.body) res.send('Success!') }) ``` - form tag: `app.use(express.urlencoded({extended: false}));` - JSON: `app.use(express.json())` ## RESTful API - url parameters should make sense - http request is the verb, and the url is the noun - stateless: calls can be made independently of one another ### Request Properties Most used properties of request: - req.query - `?key1=value1&key2=value2` - req.body - use `app.use()` middleware to send it to the body - req.headers - req.params - e.g. `:id` If there are more than 1 params e.g. `/user/:name/:date` , req.params will return an object. ```javascript // 127.0.0.1:3000/users/tom/0423 { name: 'tom', date: '0423'} ``` - req.query - e.g. `?q="hello"` ```javascript app.get('/users/:name', functions(req,res){ const myName = req.params.name; const query = **req.query** res.send('<html><head></head><body><h1>'+myName+'</body></html>') }) // 127.0.0.1:3000/users/tom?q=hello&limit=30 {q: 'hello', limit: '30'} ``` ### Response Properties Most used properties of response - res.status() - `res.status(404)` - res.send() ```jsx app.get('/:id', (req, res) => { // console.log(req.query) // console.log(req.headers) // console.log(req.body) // console.log(req.params) res.status(404).send('Not Found!') res.send('getting root'); }); ``` ### Sending a static file 1. create a `public` folder 2. inside `public` folder, create an `index.html` file 3. send a static file ```javascript const app = express() app.use(express.static(__dirname + '/public')) ``` - `express.static()` :::info **`__dirname` does not work in ES modules.** Solutions: 1. Change it back to Common JS: remove “type”: “module” in the package.json file 2. Add these lines to sever.js file ```javascript import path from "path" const __dirname = path.resolve() ``` ::: ## Node File System Module ### Read file hello.txt: ```javascript helllooo there!! ``` script.js: ```javascript const fs = require('fs'); // Using the built-in 'fs' module // asynchronous: is going to continue read through the file, when it's done, execute the call back fs.readfile('./hello.txt', (err, data) => { if (err) { console.log('errrorrrr'); } console.log('Async', data.toString()); }) // synchronous const file = fs.readFileSync(’./hellotxt’); // is going to hault the file console.log('Sync', file.toString()) // Expected Output // Sync helllooo there!! // Async helllooo there!! ``` - `const fs = require('fs');` - access the `fs` module - `fs.readfile()` - `''` - path - `(err, data) ⇒ {}` - function with `err` and `data` parameters - `.toString()` - default param - `.toString('utf8')` : type of encoding, mostly used in web - `fs.readFileSync(’./hellotxt’)` #### `readFile()` vs. `readFileSync()` - `readFile()` is **async**: will continue to read through the file, and until it’s done it will continue execute the callback function - `readFileSync()` is **sync**: will block the file until it’s done ### Append to File ```javascript appendFile() ``` script.js: ```javascript // APPEND fs**.appendFile**('./hello.txt', ' This is so cool!', err => { if(err){ console.log(err) } }) ``` hello.txt: ```javascript helllooo there!! This is so cool! ``` ### Add File ```javascript .writeFile() ``` ```javascript // WRITE fs.writeFile('bye.txt', 'Sad to see you go', err => { if (err) { console.log(err) } }) ``` created a new file: bye.txt ```javascript Sad to see you go ``` ### Delete File ```javascript .unlink() ``` ```javascript //DELETE fs.unlink('./bye.txt', err => { if (err) { console.log(err) } console.log('Inception') }) ``` → bye.txt is removed