我正在进行服务器端API调用。用户可以输入成分和搜索。提交数据后,我在终端上看到这是我的API调用:
“http://www.recipepuppy.com/api/?i=[object Object]”。
我希望它看起来像这样:
“http://www.recipepuppy.com/api/?i=milk,flour,sugar,egg”
这是我的代码:
router.get("/whatCanIMake", function(request, response){
var inputIngredients = request.query;
var ingredientString = "";
console.log(inputIngredients);
for (var i = 0; i<inputIngredients.length; i++){
ingredientString += inputIngredients[i] + ",";
}
var api = "http://www.recipepuppy.com/api/?i=" + inputIngredients + "";
console.log(api);
console.log("inputingredients", inputIngredients);
request.get(api, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
});
答案 0 :(得分:0)
我会使用Lodash _.forEach方法:
https://lodash.com/docs#forEach
var ingredientString = "";
_.forEach(inputIngredients, function(value,key){
if(ingredientString.length != ""){
ingredientString += "," + value;
}
else {
ingredientString = value;
}
});
答案 1 :(得分:-1)
router.get("/whatCanIMake", function(request, response){
var inputIngredients = request.query;
var ingredientString = "";
console.log(inputIngredients);
//for (var i = 0; i<inputIngredients.length; i++){
// ingredientString += inputIngredients[i] + ",";
//}
for (var property in inputIngredients)
{
if (inputIngredients.hasOwnProperty(property)) {
ingredientString += property + ",";
}
}
//这里的其余代码