# Express Basics

\ <br>

![image-20200331092006288](https://199941116-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M6ivT9AfNVmiT1Q6B2U%2Fuploads%2Fgit-blob-87f865c22040766c2f440d5629b7e6e1cf6a167f%2Fimage-20200331092006288.png?alt=media)

\ <br>

### What is Express.js?

: Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop `web` and `mobile` applications.

<br>

#### Core Features

1. Allows to **set up middlewares** to respond to HTTP Requests
2. Defines a **routing table** which is used to perform different actions based on HTTP Method and URL
3. Allows to **dynamically render HTML Pages** based on passing arguments to templates

\ <br>

## Installation

<br>

### 1. Installing Express Locally

> Install express

```bash
npm install express --save
```

* saves the installation locally in the **node\_modules**
* create a directory **express** inside **node\_modules**

<br>

> Express version check

```bash
$ npm view express version
4.17.1
```

<br>

> Install modules along with express

```bash
npm install body-parser --save
npm install cookie-parser --save
npm install multer --save
```

\ <br>

### 2. Installing Express in the Project

<br>

#### Directory structure

```
express_tutorial/
├── package.json
├── public
│   └── css
│   └── style.css
├── router
│   └── main.js
├── server.js
└── views
 ├── about.html
 └── index.html
```

<br>

#### 1. create package.json

```json
{
  "name": "express-tutorial",
  "version": "1.0.0",
  "dependencies":
  {
    "express": "~4.13.1",
    "ejs": "~2.4.1"
  }
}
```

\ <br>

#### 2. Install dependency by using `npm`

```bash
npm install
```

\ <br>

#### 3. Create `Express` server

> server.js

```javascript
var express = require('express');
var app = express()
var server = app.listen(8000, function(){
    console.log("Express server running on port 8000!")
})
```

<br>

> result

```bash
$ node server.js
Express server running on port 8000!
```

* When opening the web server on port 8000, the text `Cannot GET/` is displayed
  * why?
    * Because the `Router` hasn't been set up yet!

\ <br>

#### 4. Basic Routing

<br>

> server.js

```javascript
var express = require('express');
var app = express()
var server = app.listen(8000, function(){
    console.log("Express server running on port 8000!")
})

app.get('/', function(request, response){
    response.send('Hello World')
})
```

\ <br>

#### 5. Router

<br>

![image-20200403223235009](https://199941116-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M6ivT9AfNVmiT1Q6B2U%2Fuploads%2Fgit-blob-cd1856084c29b12ddeb43ebf12f1eb208fd3a741%2Fimage-20200403223235009.png?alt=media)

It is good coding practice to write router code and server code in separate files!

* Create a **router** folder
* Create `main.js`

<br>

> router > main.js

```javascript
module.exports = function(app){

    app.get('/', function(request, response){
        response.render('index.html')
    });

    app.get('/about', function(request, response){
        response.render('about.html')
    });
}

```

* `module.exports` allows the **router** code to be imported and used as a module in `server.js` since it was written separately\~!

\ <br>

### 5. Render HTML page

<br>

* Create a **views** directory
* Create `html` files

<br>

> views > index.html

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Index</title>
</head>
<body>

<p>This is index page!</p>
</body>
</html>
```

<br>

> views > about.html

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=<device-width>, initial-scale=1.0">
    <title>About</title>
</head>
<body>
    <p>About... what?</p>
</body>
</html>
```

<br>

> Modify server.js

```javascript
var express = require('express');
var app = express();

// Import the router module main.js and pass app to it
var router = require('./router/main')(app);

// Define the location of HTML so the server can read it
app.set('views',__dirname + '/views');

// Set the server to use the EJS engine when rendering HTML
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);

var server = app.listen(8000, function(){
    console.log("Express server has started on port 8000!!")
})
```

\ <br>

### Handling Static Files

<br>

#### Static Files

* `.js`, `css`, `image` files used in HTML
* To handle `Static files` on the **Server**, use the `express.static()` method!

<br>

1. Create a **public** directory
2. Create a **css** directory
3. Create `.css` files

<br>

> public > css > style.css

```css
body {
    background-color: black;
    color: white;
}
```

<br>

> Modify server.js

```javascript
// Set the public directory as the static folder
app.use(express.static('public'));
```

<br>

> Add CSS link to html files

```html
<link rel="stylesheet" href="css/style.css">
```

<br>

#### result

> 127.0.0.1:8000/

![image-20200404155824643](https://199941116-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M6ivT9AfNVmiT1Q6B2U%2Fuploads%2Fgit-blob-050de48752b02e9a9eeeb377ad0d5115522cab2f%2Fimage-20200404155824643.png?alt=media)

<br>

> 127.0.0.1:8000/about

![image-20200404155934497](https://199941116-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M6ivT9AfNVmiT1Q6B2U%2Fuploads%2Fgit-blob-6848b8ed1566d843bd042f97c6060c0fae4516d2%2Fimage-20200404155934497.png?alt=media)

<br>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://chloe-codes1.gitbook.io/til/node.js/express.js/01_express_basics.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
