Node.js HTTP:对客户端的反向响应的行业标准
大家好,我是网络开发新手,所以我正在开发一本简单的在线食谱,让我在这个过程中也可以学习节点和角度 在post请求或delete请求的情况下,我是如何挣扎于应该将哪种类型的响应发送回客户端以获得成功,还是失败 以下是api POST访问点的示例:Node.js HTTP:对客户端的反向响应的行业标准,node.js,mongodb,http,frontend,httpbackend,Node.js,Mongodb,Http,Frontend,Httpbackend,大家好,我是网络开发新手,所以我正在开发一本简单的在线食谱,让我在这个过程中也可以学习节点和角度 在post请求或delete请求的情况下,我是如何挣扎于应该将哪种类型的响应发送回客户端以获得成功,还是失败 以下是api POST访问点的示例: app.post('/recipe/',(req,res)=>{ res.set({ 'Access-Control-Allow-Origin': 'http://localhost:4201' }) console.log(&
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
}
异步添加配方(recipeName,配料){
如果(成分==null){
返回null;
}
if(recipeName==null){
返回null;
}
var配方=新配方(recipeName,配料);
if(recipe.getComponents().length idk)关于任何行业标准,但您可以做什么来修复每次调用时都会返回的对象。类似于{“status”:true,“data”:{your data},“message”:“any message here”}
。如果预期操作成功,则您将在状态中返回true,否则返回false,data
中的任何json数据和message
key@RohitAmbre谢谢你的回复。这个想法对我来说很有意义,我将重构我的代码以适应这个模型。再次感谢你!说实话,没有严格的规则,这些只是约定,我强烈建议大家看一看,这是一个非常好的例子,但最好的做法是使用http代码而不是响应,以使服务器端的操作更清晰201
用于POST操作,而204
用于删除操作IDK关于任何行业标准,但您可以做什么来修复每次调用时返回。类似于{“status”:true,“data”:{your data},“message”:“any message here”}
。如果预期操作成功,则您将在状态中返回true,否则返回false,data
中的任何json数据和message
key@RohitAmbre谢谢你的回复。这个想法对我来说很有意义,我将重构我的代码以适应这个模型。再次感谢你!说实话,没有严格的规则,这些只是约定,我强烈建议大家看一看,这是一个非常好的例子,但最好的做法是使用http代码而不是响应,以使服务器端的操作更清晰201
用于POST操作,而204
用于删除操作