【发布时间】:2020-07-27 12:32:20
【问题描述】:
我正在编写一个食谱搜索引擎,但由于我以前没有使用过后端(我是编码初学者),所以我一直在客户端和服务器之间发送数据。
在客户端,我要求用户选择他想要食谱的类别(例如鸡肉)。
然后选择保存在变量中,并发送到服务器。一切正常。
然后在服务器上我想将类别传递给 API 调用,进行调用并将数据发送回客户端,我该怎么做?
这是一些代码:
客户端:
function getRecipes(category){
const categorySearch = category.alt;
let data = {
categoryChoice: categorySearch
}
let options = {
method: 'POST',
headers: {
"Content-type": "application/json; charset=UTF-8"
},
body: JSON.stringify(data)
}
const promise = fetch('/data', options);
promise.then(response => {
if(!response.ok){
console.error(response)
} else {
return response.json();
}
}).then(result => {
console.log(result);
})
}
服务器端
app.post('/data', async (request, response) => {
const data = await request.body;
const gotData = data.categoryChoice;
const category = gotData;
console.log(category);
response.json(category);
return category
})
app.get('/data', async (request, response) => {
const cat = await category;
const url = `https://edamam-recipe-search.p.rapidapi.com/search?q=${cat}&from=0&to=100`
const fetch_response = await fetch(url);
const json = await fetch_response.json();
response.json(json);
})
app.get 没有记录或给我任何东西,所以我认为它甚至不起作用
【问题讨论】:
标签: javascript node.js server client