DEV Community

Brix Mavu
Brix Mavu

Posted on

Day 4

The idea is to make a simple login with express

copy day3 folder into day4 folder

moving just contents from one folder into next folder in same root folder in terminal

cp -r folder1/* folder2

create folder authenticate

mkdir authenticate

Inside authenticate folder create new file login.js

touch login.js

Paste this code

const login = function (user,password) {
    if(user==="brix" && password==="brix"){
        return true;
    }
    else{
        return false;
    }

}

module.exports = login
Enter fullscreen mode Exit fullscreen mode

Edit

You have to add the two lines below to start working with json in express
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.js should look more like this

const express = require('express')
const path = require('path')
const login = require('./authenticate/login')

const app = express()
const port = 3000

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')))

app.get('/',(req,res) => {
  res.sendFile(path.join(__dirname,'public/index.html'));
})

app.post('/login', function (req, res, next) {
    const user = req.body.username
    const pass = req.body.password
    let loginResult = login(user,pass)

    if(loginResult) {
      //show main content
      res.send('Hello World Again!')
    }else{
      //show error 
    }

})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)