【问题标题】:using fetch API with NodeJS(express)使用 fetch API 和 NodeJS(express)
【发布时间】:2020-11-22 13:24:23
【问题描述】:

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

堆栈信息:用于前端的 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.

这是路线和相关功能:

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 调用,而且我对 Promise 很陌生,可能并不完全理解它们。

【问题讨论】:

    标签: javascript node.js ajax fetch-api


    【解决方案1】:

    您应该在 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);
          }
        });
    

    回复状态和发送的方法有很多种,大家可以相应的查看和使用

    【讨论】:

    • 感谢您的回答。为什么我们在这里使用 next(err)?
    • 接下来,这里我们主要用于nodejs中的中间件路由。它基本上将控制权传递给下一个匹配的路线。在您的情况下,您可以忽略下一个并尝试使用第二个块
    猜你喜欢
    • 2016-11-25
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    相关资源
    最近更新 更多