node.js - 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(); 返回的大量对象;
如果成功和失败符合行业标准,我应该向客户发送什么?
解决方案
推荐阅读
- c# - 从 .Net Core 3.1 迁移到 .NET 5
- python - 如何让用户在 django 中拥有他们的数据
- java - 如何制作像 Instagram 一样的滑动对话框?
- spring-boot - AbstractCouchbaseDataConfiguration.class 无法打开,因为它不存在
- windows-subsystem-for-linux - 如何重新安装 WSL?无济于事总是同样的错误
- sql - 使用 YYYY-MM-DDtHH-MM-SS (BigQuery) 从 SQL 表中获取最近 30 天
- c# - HttpResponseMessage 不获取非 ascii 字母
- r - 如何使用 tidyverse 根据某些条件添加新列?
- amazon-redshift - Oracle 到 Redshift 查询
- django - 如何从 modelformset_factory 访问单个表单对象?