简体   繁体   English

使用 fetch API 和 NodeJS(express)

[英]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.堆栈信息:MongoDB,NodeJS(Express),前端的 VanillaJS。

I am using fetch API on the client-side and promises on the server-side.我在客户端使用 fetch API 并在服务器端使用 promise。

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.我从输入元素中获取值,然后对检查数据库中的值的路由进行 AJAX 调用。 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:这是路线和相关的 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:这是前端 javascript 代码:

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. PS:这是我第一次使用这样的 AJAX 调用,而且我对 promises 很陌生,可能并不完全理解它们。

you should use a try-catch block in express as all errors should be handled manually.您应该在 express 中使用 try-catch 块,因为所有错误都应手动处理。 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响应状态和发送的方法有很多,您可以相应地检查和使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM