Shantanu Kaushik
Shantanu Kaushik

Reputation: 55

using fetch API with NodeJS(express)

I am making an app and adding functionality to it that checks in real-time if a username is already taken or not.

Stack info: MongoDB, NodeJS(Express), VanillaJS for the front end.

I am using fetch API on the client-side and promises on the server-side.

What am I doing here:

I am taking the value from the input element and then making an AJAX call to a route that checks the database for the value. If the database returns some data then it means that the username is already taken if no data is returned then it is available for use.

The Error message which I am Getting is ==>

(node:1697) UnhandledPromiseRejectionWarning: username already in use
(node:1697) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, 
or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:1697) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

This is the route and associated function:

app.get("/api/check/:username", (req,res)=>{
    checkDuplicate(req,res);
});
function checkDuplicate(req, res) {
    return new Promise(function(resolve, reject){
        User.findOne({username: req.params.username}, function(err, data){
            //no data found, username availabe
            if(!data){
                resolve();
            //database error
            }else if(err){
                reject("some error occurred");
            //data found, user already exist
            }else{
                reject("username already taken");
            }
        });
    });
}

this is the front end javascript code:

fetch(`/api/check/${username.value}`)
            .then(showMessage("username Availabe, you are ready to go"))
            .catch(err => showMessage(err, true));

PS: this is the first time that I am using AJAX calls like this and also I am quite new to promises and probably don't completely understand them.

Upvotes: 1

Views: 3345

Answers (1)

Hrishikesh Kale
Hrishikesh Kale

Reputation: 6568

you should use a try-catch block in express as all errors should be handled manually. try replacing the block

app.get("/api/check/:username", async (req,res,next)=>{
try {
   const result = await checkDuplicate(req,res);
    res.send(result);
  } catch (err) {
    next(err);
  }
});

as I see you want to reject error and pass it to frontend you have do handle it like

app.get("/api/check/:username", async (req,res,next)=>{
    try {
       const result = await checkDuplicate(req,res);
        res.send(result);
      } catch (err) {
        res.send(err);
      }
    });

there are many methods of response status and send you can check and use accordingly

Upvotes: 1

Related Questions