问题描述
大家好,我是Web开发的新手,所以我正在开发一本简单的在线食谱,使我也可以在此过程中学习节点和角度。
在发布请求或删除请求的情况下,我应该如何将哪种类型的响应发送回给客户端以求成功或失败,我一直感到困惑。
以下是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();
返回的庞大对象。如果成功和失败符合行业标准,我应该向客户发送什么?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)