Learning through mistakes in MERN

Learning through mistakes in MERN

Learning through mistakes

While we learn to code. The most disheartening things for us are bugs and errors.

I don't know whether people feel the same while working, but it feels really embarrassing while learning.

However, it is a part of the process and we must keep going.

Also in languages like Javascript and python which doesn't have types,

things even get trickier.

Therefore I have compiled a few common errors I got and utilised them for my learnings.

This will surely benefit any starter, starting to learn Node.js or

Committed node_modules

I did

git add .

git commit -m “Message”

Its common but here is the tricky thing.

I did not put node_modules in the .gitignore This was a mistake.

Now the fix is to add the node_modules into the .gitignore

Next, commit it.

Now we need to remove it from the cache the below command.

git rm --cached -r node_modules/

Didn’t save the Atlas DB password.

Go to cloud.mongodb.com

Select the Project Name there is a 📁 symbol on the page;

Go to Database Access under the Security Section

Edit the user password.

Also add Built-in Role under Database User Privileges.

To allow read-write access

Connecting Frontend and backend running on different ports or servers.

We need to import cors in our routing page. Below is the sample code.

const cors = require('cors');

// So that pages are served even from being in the different port or server
app.use(cors());

//here app= require('express')()

Updating the front end to connect to the different ports for the backend.

We need to add an endpoint in the anchor tag or

the buttons or the functions calling the backend.

To make the correct calls.

You may replace http://localhost:3000 with your public server IP and port.

<script>
    const links = document.querySelectorAll('a[data-endpoint]');

    links.forEach(link => {
      link.addEventListener('click', event => {
        event.preventDefault();
                // the localhost to be running the server on port:3000
        const endpoint = `http://localhost:3000${link.dataset.endpoint}`;
        fetch(endpoint)
          .then(response => {
            if (!response.ok) {
              throw new Error('Network response was not ok');
            }
            return response.text();
          })
          .then(data => {
            console.log(data);
            // Handle the response as needed
          })
          .catch(error => {
            console.error(error);
          });
      });
    });
  </script>

Messed up with the sendFiles

Let me tell you something first.

Folder structure

frontend/
    Public/
    chat.html
    expertSignUp.html
    index.html
    userSignUp.html
    contactUs.html
    funTime.html

Backend/
    index.js
    package.json
    .env
    models/
        Authoriy.js
        crossWord.js
        entity.js
        quiz.js
        rootAuthority.js
        user.js

Now in the index.js I wanted to have the routing for the frontend

I tried this and failed.

const express = require("express")

const app = express()

app.get('/funTime', function (req, res) {
    res.sendFile("../frontend/funTime.html",{root: __dirname});
}

As the root: __dirname is wrong.

It should be

res.sendFile('funTime.html', { root: path.join(__dirname, '../frontend') });

As the root is for the actual folder where the file resides.

Now these are a few working options, apply anyone.

Working solutions

I personally like the first one as it's more readable.

    var filePath = '../frontend/funTime.html';
    var resolvedPath = path.resolve(filePath);
    res.sendFile(resolvedPath);
res.sendFile(path.join(__dirname, '../frontend/funTime.html'));
res.sendFile('funTime.html', { root: path.join(__dirname, '../frontend') });
res.sendFile(path.join(__dirname, '../frontend/funTime.html'));

Wrong way of writing the port

I wrote the below which is wrong

app.listen(3001,()=> {
    console.log('App running at http://localhost/3001')
})

We add an : after localhost to specify the port

The correct way is

app.listen(3001,()=> {
    console.log('App running at http://localhost:3001')
})

Until now I have had these bugs and errors. Learning is awesome.

I am continuously learning and will keep updating when I get more errors and bugs.

Feel free to suggest any improvements and comments.

Hope you have an amazing journey.

Happy CODing