提问者:小点点

在服务器和客户机之间发送数据的JavaScript/Node.js


我正在编写一个食谱搜索引擎,我一直在客户端和服务器之间发送数据,因为我以前没有使用后端(我是一个编码初学者)。

在客户端,我要求用户选择他想要食谱的类别(例如鸡肉)。
然后选择保存在变量中,并发送到服务器。 一切正常。
然后在服务器上,我要将类别传递给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不记录或给我任何东西,所以我认为它根本不起作用


共2个答案

匿名用户

请尝试以下操作:

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`
    fetch(url).then(res => res.json()).then(res => {
        response.json(json);
    });
})

匿名用户

我认为您应该只使用'get'方法(在前端和后端)。 假设您的代码是正确的,它应该是这样的:

app.get('/data', async (request, response) => {
    const data = request.body;
    const category = data.categoryChoice;
    console.log(category);
    const url = `https://edamam-recipe-search.p.rapidapi.com/search?q=${category}&from=0&to=100`
    const fetch_response = await fetch(url);
    const json = await fetch_response.json();
    response.json(json);
})