首页 > 解决方案 > HTTP:返回客户端响应的行业标准

问题描述

大家好,我是网络开发的新手,所以我正在开发一个简单的在线食谱书,让我也可以在这个过程中学习节点和角度。

在发布请求或删除请求的情况下,我如何为成功和失败发送回客户端的响应类型而苦苦挣扎。

这是一个 api POST 访问点的示例:

app.post('/recipe/',(req,res)=>{

res.set({
    'Access-Control-Allow-Origin': 'http://localhost:4201'
  })

  console.log("Recieved req at /recipe/")
  if(req.body.recipe === undefined){
      res.send("Request not filled. No recipe found");
  }
  if(req.body.ingredients === undefined){
      res.send("Request not filled. No ingredients found");
  }
  //var r = new Recipe(req.body.recipe,req.body.ingredients);
  mongo.addRecipe(req.body.recipe,req.body.ingredients).then((promise)=>{
      mongo.getAllRecipeByName().then(promise=>{
          console.log(promise);
      });

      res.send(promise);
  })
})

这是 mongo.addRecipe() 的代码,因此您知道该承诺中返回的内容:

    async addRecipe(recipeName,ingredients){
   if(ingredients == null){
       return null;
   }
   if(recipeName == null){
       return null;
   }
    var recipe = new Recipe(recipeName,ingredients);
   if(recipe.getIngredients().length <= 0){
       return null;
   }

    try{
        const client = new MongoClient(this.uriString);
        
        await client.connect();
        const db = client.db(this.databaseString);
        const recipeCollection = db.collection(this.collectionString);
        
        var status = await recipeCollection.insertOne(recipe);
        client.close();
        if(status.acknowledge == true){
            return status
        }
        else{
            return status
        }
        //console.log(await recipeCollection.find({recipeName:recipeName}).toArray());
    
    }
    catch(e){
        console.error("Failed addRecipe() params: "+recipeName+" "+ingredients+e);
        return null;
    }
    //String recipeName  List<String> ingredients
    //creates connection with mongo database.
    //add {name:'recipeName',ingredients:'ingredients'} to mongoDB
    
}

因此,您可以看到我的一些验证语句返回 null,然后我将 null 发送回客户端。这是一个错误吗?在成功的情况下,我将返回从 collection.insertOne(); 返回的大量对象;

如果成功和失败符合行业标准,我应该向客户发送什么?

标签: node.jsmongodbhttpfrontendhttpbackend

解决方案


推荐阅读