繁体   English   中英

使用 fetch API 和 NodeJS(express)

[英]using fetch API with NodeJS(express)

我正在制作一个应用程序并为其添加功能,以实时检查用户名是否已被使用。

堆栈信息:MongoDB,NodeJS(Express),前端的 VanillaJS。

我在客户端使用 fetch API 并在服务器端使用 promise。

我在这是要干嘛:

我从输入元素中获取值,然后对检查数据库中的值的路由进行 AJAX 调用。 如果数据库返回了一些数据,则表示该用户名已被使用,如果没有返回数据,则可以使用该用户名。

我收到的错误消息是 ==>

(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.

这是路线和相关的 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");
            }
        });
    });
}

这是前端 javascript 代码:

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

PS:这是我第一次使用这样的 AJAX 调用,而且我对 promises 很陌生,可能并不完全理解它们。

您应该在 express 中使用 try-catch 块,因为所有错误都应手动处理。 尝试更换块

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

正如我所见,您想拒绝错误并将其传递给前端,您确实可以像这样处理它

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

响应状态和发送的方法有很多,您可以相应地检查和使用

暂无
暂无

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

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