【问题标题】:Javascript/node.js sending data between server and clientJavascript/node.js 在服务器和客户端之间发送数据
【发布时间】: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


    【解决方案1】:

    试试这个:

    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);
        });
    })
    

    【讨论】:

    • 不,仍然什么都没有
    【解决方案2】:

    我认为您应该只使用一种“发布”方法(在前端和后端)。假设你的代码是正确的,它应该是这样的:

    app.post('/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);
    })
    

    【讨论】:

    • 我收到此错误:recipes.js:126 POST http://localhost:3100/data 404 (Not Found)
    • 您是否将客户端的方法更改为“GET”?
    • 是的,但是我无法将带有类别的正文发送到服务器。无论如何我已经设法解决了。我已将 API 调用移至 app.post 部分并且有效:)
    猜你喜欢
    • 2022-06-24
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 2011-10-12
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多