Quick Express
Posted on October 2, 2021
Tags: javascript
1 POST request
- update means you cant natively grab data from POST request
- you require a
bodyParser
let urlencodedParser = bodyParser.urlencoded({ extended: false })
.post('/register', urlencodedParser, async (req,res) => {..} app
2 async await
- await just wraps the rest of the codeblock inside a
.then(()=>...)
- the below 2 code are equivalent
await f()
console.log('hi')
.then(()=> console.log('hi')) f
- async/await REQUIRE functions that return promises
//BAD - DOESNT WORK
const rawDB = await fs.readFile("accounts.json",(err,data) => { return data})
console.log(rawDB);
//GOOD - we wrap the readFile into a promise
const readFilePromisfied = async (filepath) => {
return new Promise((resolve,reject) => {
.readFile(filepath,'utf-8', (err,data)=>{
fsif (err) {reject(err)};
resolve(data);
})
})
}
const rawDB = awaitreadFilePromisfied("accounts.json");
console.log(rawDB);
3 Login Registration system
- Password Hashing is only done on server-side
- This way even if a hacker stole the hashed password:
- Attempt 1: Enter hashed-pass into client login, -> double hashed password which fails login
- Attempt 2: Tries to get plaintext pass but can’t due to hash being one-way function
- This way even if a hacker stole the hashed password:
- Server Registration system
bcrypt.hash(plaintextpass,saltrounds)
is stored with the newly registered username
- Server login system
- search record for submitted login username then compare pass
bcrypt.compare(plaintextpass,hashedpass)
for comparing plaintext pass submission and DB hashed passjwt.sign(username)
for giving access to member-services
Notice BOTH Registration and Login require bcrypt for hashing and hashcomparison.
ONLY Login requires JWT for stateful access to member-services.
4 Dynamic routes
- data is stored in
req.params.____
- all routes need
res.send()
or else any visitor will get a (pending)
.get('/:bleh', (req, res) => {
appconsole.log(req.params.bleh)
.send(req.params.bleh)
res })