簡體   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