---
# System prepended metadata

title: Backend2

---

# Backend2

- Checkout out [Backend1](/aEfm2kugTjS_1X2ki0glRg) first!
- Clone the project
    - git@github.com:icesplendent/TutorialExpress.git

## Prerequisite

- What we need
    - `nodemon` `express` 
    - `cross-env` `dotenv`
    - `uuid` `moment` `cors`



## Get Started


```javascript=
const express = require('express');

const app = new express();

const PORT = process.env.PORT || 8000;

app.listen(PORT, () => console.log(`Server is running at PORT ${PORT}`))
```

## Set Static folder
```javascript=
app.use(express.static(path.join(__dirname, 'public')));
```

## Middleware
```javascript=
// middleware
const logger = (req, res, next) => {
    console.log(`${req.protocol}://${req.get("host")}${req.originalUrl}`);
    next(); // the next function to go
};

// Init middleware
app.use(logger);
```

## [Body Parser](https://ithelp.ithome.com.tw/articles/10241083)
```javascript=
app.use(express.json());
```


## Learn from the Code
```javascript=
app.use(
  (req, res, next) => {
    if (req.url === '/home') {
      fs.readFile(path.join(__dirname, 'public', 'home.html'), (err, data) => {
        if (err) throw err;
        res.writeHead(200, {'Content-type': 'text/html'});
        res.end(data)
      })
    }
  }
)
```