---
# System prepended metadata

title: server/index.js

---

# Intro to web app

## file structure
```
server
 - index.js
web-1
 - index.js
 - index.html
 - index.css
```


## To get started

```
cd web-1/index.html
```

add this code

```html=
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="index.css">
    
    <title>
        Web intro
    </title>
</head>

<body>
    <h1>Intro to web app</h1>

     <script src="index.js"></script>
</body>

</html>
```

take note of what is in the 

```html
<title>
...

<link rel="stylesheet" href="index.css">
...

</title>
```

go to the `index.css` file and add

```css=
body {
    background: #000;
    color: #fff;
    
}
```

In vscode make sure you checkout the extensons section, search for `live server, thunder bolt`

Right click on any html section and choose `open server`, go to your browser, confirm that you have your website up

open `web-1/index.js` and add
```javascript=

async function fetchData() {
    try {
        const response = await fetch('http://localhost:3000/api');
        const responseContainer = document.getElementById('responseContainer');
        
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        
        const data = await response.json();
        responseContainer.textContent = JSON.stringify(data, null, 2); 
    } catch (error) {
        console.error('Error fetching data:', error);
    }
}



document.addEventListener("DOMContentLoaded", fetchData)


```

```
cd /servers
```

run

```
npm init -y
```

install packages by running

```
npm i express body-parser
```

add the following code to 

```
server/index.js
```


```javascript=
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')

const router = express.Router()

const app = express()
const port = 3000

// security flaw
app.use(cors())


app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.static('public'))


router.get('/', (req, res) => {

    // connect to external db, mysql
    // authentication
    const
        books = [
            {
                id: 1,
                author: 'bill graham',
                title: 'road to salvation'

            },
            {
                id: 2,
                author: 'Margret Ogolla',
                title: 'River and the source'

            },
            {
                id: 3,
                author: 'John Kiriamete',
                title: 'My life in crime'

            },
        ]

    res.send(
        books
    )
})

// auth middleware 
app.use('/api', (req, res, next) => {

    const auth = false // req.headers // session token // credentials

    // To parse some headers
    // If condition to check the credentials
    // If you are not planning for bruteforce attacks, there is high chance of it happening here

    if (auth) {
        next()
    }

    res.send({error:"Yo do not have permissions to get access to this resource"})


})


app.use('/api', router)


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


Then execute the file

make sure you are in 

```
server/index.js
```

use command

```
node index.js
```

Go to `localhost:3000` on any of your browser, what is the response you see