Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# My Route was not working :/

Everything seemed ok.
But I got no output for this route

<details>
<summary> login route </summary>

```javascript
// to check user login
app.post('/users/login', async (req, res) => {
const user = users.find(user => req.body.name === user.name)
if (user === null) {
return res.status(401).send('Cannot find the user.')
}
console.log(user)
try {
if (bcrypt.compare(req.body.password, user.password)) {
res.status(200).send('success')
console.log('success')
}
else {
res.status(401).send('Not allowed')
}
}
catch {
res.status(500).send("Invalid user")
}
})

```

</details>

<details>
<summary>Also now corrected a simple mistake </summary>

```javascript
// to check user login
app.post('/users/login', async (req, res) => {
const user = users.find(u => req.body.name ===u.name)
if (user === null) {
return res.status(401).send('Cannot find the user.')
}
console.log(user)
try {
if ( await bcrypt.compare(req.body.password, user.password)) {
res.status(200).send('success')
}
else {
res.status(401).send('Not allowed')
}
}
catch {
res.status(500).send("Invalid user")
}
})
```

</details>

- I identified my mistakes
- I forgot to write the await before the bcyrpt.compare
- I wrote
```const user = users.find(user => req.body.name === user.name)```
INSTEAD OF
```const user = users.find(u => req.body.name ===u.name)```

I asked Perplexity.ai there was no error.
Then I told it about my fetch request.
which looked like this.

```javascript
const options = {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: '{"name": "Kunarl", "password": "fksdfh34234,wrw"}'
};

fetch(`localhost:$(PORT)/users/login`, options)
.then(response => console.log(response))
.catch(err => console.error(err));
```

It said I should try putting <http://localhost:$(PORT)/users/login>
This worked and I am feeling good and silly
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# I learnt about the bodyparser the hard way

## What exactly happened?

I was trying to get some data from requests.
It didn't work.

<details>

<summary> <b>server.js</b> </summary>

```javascript
const express = require("express")
const app = express()
const bcrypt = require("bcrypt")

const users = [{ name: "Demo", password: "wohoa235#21" }]
// This is just for the basic project.
//In real use case we will get from the server db sql/no sql

app.listen(8002, () => {
console.log("Server started\n Listening on http://localhost:8002")
})

// also we will add middleware route to check if user making the request
// has the permission to post or get on this route.
app.post('/users', async (req, res) => {
try {
const salt = await bcrypt.genSalt()
debugger
console.log(req.body)
console.log(req.body.name," : ", req.body.password)
const hashedPassword = await bcrypt.hash(req.body.password, salt)
const user = { name: req.body.name, password: hashedPassword };
users.push(user);
res.status(201).send(user);
console.log("Newly added user: ",users[users.length-1])
}
catch(err){
console.log(err.message);
res.status(500).send()
}
})

app.get("/", (req, res) => {
res.send("Yeah connected");
})

app.get('/users', (req, res) => {
res.json(users);
})

app.get("/:page", (req, res) => {
res.send(`We are working on ${req.params.page}`)
})
```

</details>

## Missing piece

I needed body-parser.
But I thought let's just do it using express.json() .
Since I am using express anyways.

so I used express.json()
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Again I know figured it out looking objectively.
That bcrypt.compare is async so now I put the await and it works well.
31 changes: 31 additions & 0 deletions Express Js/OAtulA/UserAuth/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# UserAuth

## About

So this is a basic user authentication express.js app.

You can
- POST /signup register user to route
- PUT /users/password to update password
- PUT /users/name to update name
- DELETE /users/remove to delete a user
- POST /users/login to login user
- GET /users to see all users

You can look at Thoughts/req_body.txt to see the content template for the requests.

You can try and run Request tests/post-user2.js to check the routes.

I have used this

```
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "node --watch server.js"
},
```

So the ```node --watch``` is available only for version >= Node.js 18.11.0
The --watch flag was added to Node.js in version 18.11.0

You might want to use nodemon installed as global to check this out.
5 changes: 5 additions & 0 deletions Express Js/OAtulA/UserAuth/Request tests/Bunch-of-users.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Mehul fsdlfh2324
Piyush 23423hsdkjfhsdk
Kunarl fksdfh34234,wrw
Kishauma fsdhf421*7
Nourami sdfh3,87
9 changes: 9 additions & 0 deletions Express Js/OAtulA/UserAuth/Request tests/Login.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const options = {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: '{"name": "Kunarl", "password": "fksdfh34234,wrw"}'
};

fetch('http://localhost:8002/users/login', options)
.then(response => console.log(response))
.catch(err => console.error(err));
73 changes: 73 additions & 0 deletions Express Js/OAtulA/UserAuth/Request tests/post-user2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
const fs = require('fs')
let format_user=[];
fs.readFile('Bunch-of-users.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
users = data;
newUsers = users.split('\n')
console.log('newUsers= ', newUsers)
format_user = newUsers.map(user => {
user2 = user.split(' ');
new_user = { name: user2[0], password: user2[1] };
return new_user;
});

console.log('format_user=',format_user)
console.log(format_user.length)
for(let i=0; i< format_user.length; i++ )
{ let user = format_user[i];
fetch('http://localhost:8002/signup', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: user.name,
password: user.password
})
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Error creating user');
}
})
.then(data => {
console.log('New user created:', data);
})
.catch(error => {
console.error('Error:', error);
});
}
});
// console.log(format_user.length)
// format_user.forEach(user =>
for(let i=0; i< format_user.length; i++ )
{ let user = format_user[i];
fetch('http://localhost:8002/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: user.name,
password: user.password
})
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Error creating user');
}
})
.then(data => {
console.log('New user created:', data);
})
.catch(error => {
console.error('Error:', error);
});
}
20 changes: 20 additions & 0 deletions Express Js/OAtulA/UserAuth/Thoughts/req_body.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
For the normal requests the body will look like this.
`
body: JSON.stringify({
name: 'Aman',
password: '1245heail'
}
`
But for the put I want request
for password update
`
body:JSON.stringify({
existingUser:{
name: 'Aman',
password: '1245heail'
},
Update:{
password: 'mohan2984'
}
}
`
1 change: 1 addition & 0 deletions Express Js/OAtulA/UserAuth/USERS.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[{"name":"Demo","password":"wohoa235#21"},{"name":"Jagrit","password":"gosohds23qafhwe3.werw"},{"name":"Kushsa","password":"$2b$10$wU4rp1X6et/.SdV/CUvBve4O0zxL9Lbrci6Zr8.V94LUzFKnfBBb2"},{"name":"Mehul","password":"$2b$10$0CepIXQxYrOz1R8UMFe/4.CDPIkxjpL2l8GWciqOVpVqCknznmRLu"},{"name":"Kishauma","password":"$2b$10$NI1HLr1PZAhtY0kUNlFdle56hJ5ueslW4tuj1f1PN8yT0ZZiwlZ5i"},{"name":"Piyush","password":"$2b$10$dcuh7eMyKvXsvFyouLriq.6vmN2YA0/8GaET7fqeY6BNn0b24DCnK"},{"name":"Kunarl","password":"$2b$10$gnQVjfEXv1et7w20QAVla.NupHyy24AewUy6rjtUoQn3eVXRxOiN."},{"name":"Nourami","password":"$2b$10$Jz47Bg8LFPlviMwlRifSb.YXi7K3U8ja45evZDUKGmoJn0R7HltcS"}]
Loading