[英]return a JSON object from a GET request
I am using Node and Express to practice writing routes and was given the following exercise.我正在使用 Node 和 Express 来练习编写路线,并获得了以下练习。 Can anyone help with the response to my GET request?任何人都可以帮助回复我的 GET 请求吗? Given the follow JSON data:给定以下 JSON 数据:
{
"recipes": [
{
"name": "scrambledEggs",
"ingredients": [
"1 tsp oil",
"2 eggs",
"salt"
],
"instructions": [
"Beat eggs with salt",
"Heat oil in pan",
"Add eggs to pan when hot",
"Gather eggs into curds, remove when cooked",
"Salt to taste and enjoy"
]
},
{
"name": "garlicPasta",
"ingredients": [
"500mL water",
"100g spaghetti",
"25mL olive oil",
"4 cloves garlic",
"Salt"
],
"instructions": [
"Heat garlic in olive oil",
"Boil water in pot",
"Add pasta to boiling water",
"Remove pasta from water and mix with garlic olive oil",
"Salt to taste and enjoy"
]
},
{
"name": "chai",
"ingredients": [
"400mL water",
"100mL milk",
"5g chai masala",
"2 tea bags or 20 g loose tea leaves"
],
"instructions": [
"Heat water until 80 C",
"Add milk, heat until 80 C",
"Add tea leaves/tea bags, chai masala; mix and steep for 3-4 minutes",
"Remove mixture from heat; strain and enjoy"
]
}
]
}
I am supposed to make a GET request and return the following:我应该发出 GET 请求并返回以下内容:
{
"recipeNames":
[
"scrambledEggs",
"garlicPasta",
"chai"
]
}
This is what I have so far:这是我到目前为止所拥有的:
app.get('/recipes', (req, res) => {
const recipes = data.recipes;
const recipeNames = {}
const arr = []
for(let i = 0; i < recipes.length; i++){
let recipe = recipes[i]
let recipeName = recipe.name
arr.push(recipeName)
//recipeNames[arr] = [recipeName]
}
res.status(200).send(arr)
})
which is giving me:这给了我:
{
[
"scrambledEggs",
"garlicPasta",
"chai"
]
}
How do I get it in a JSON object with key "recipeNames" and value the array?如何使用键“recipeNames”在 JSON object 中获取它并为数组赋值?
app.get('/recipes', (req, res) => {
const recipes = data.recipes;
const recipeNames = recipes.recipeNames.map(r => r.name)
res.status(200).send({recipeNames})
})
You can make it as bellow:你可以把它做成如下:
app.get('/recipes', (req, res) => {
const recipes = data.recipes;
const recipeNames = {}
const arr = []
for(let i = 0; i < recipes.length; i++){
let recipe = recipes[i]
let recipeName = recipe.name
arr.push(recipeName)
//recipeNames[arr] = [recipeName]
}
let forSend = {"recipeNames": arr}
res.status(200).send(forSend)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.