【问题标题】:Fetching with a body vs fetching without a body (react, express)带主体获取与不带主体获取(反应,表达)
【发布时间】:2019-12-21 13:44:08
【问题描述】:

我是 Web 开发新手,在发出带有 json 正文的 fetch 请求时遇到了一些问题。现在,如果我在没有正文的情况下进行 fetch 调用,则 fetch 会连接到我的 api(记录它已连接到的日志),从我的数据库中检索值,并将它们发送回前端而不会出现问题。但是,当我将 body 对象作为第二个参数添加到我的 fetch 请求时,我的 fetch 永远不会连接到 api。没有错误输出,它只是等待,我的 api 从不记录它已连接到。

这里是代码。这有效:

//this.props.chosenInterests is an object
    async sample(){
        //url-friendly string
        const university = this.props.chosenUniversity.replace(/\s/, '+');

        const query = '/interest/' + university;

        try{
            const response = await fetch(query, {});
            if(response.ok){
                const jsonResponse = await response.json();
                globalVar = jsonResponse;

                this.forceUpdate();
            }
            else{
                throw new Error('Request Failed!');
            }
        }
        catch (error){
            console.log(error);
        }
    }

虽然没有:

//this.props.chosenInterests is an object
    async sample(){
        //url-friendly string
        const university = this.props.chosenUniversity.replace(/\s/, '+');

        const query = '/interest/' + university;

        try{
            const response = await fetch(query, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(this.props.chosenInterests)
            });
            if(response.ok){
                const jsonResponse = await response.json();
                globalVar = jsonResponse;

                this.forceUpdate();
            }
            else{
                throw new Error('Request Failed!');
            }
        }
        catch (error){
            console.log(error);
        }
    }

这是我的 api:

//already mounted router at /interest
interestRouter.get('/:university', (req, res, next) => {
    const university = req.params.university.replace(/\+/g, ' ');

    console.log('Connected.');

    db.all('SELECT * FROM Table WHERE Table.university = $university', {$university : university},
        (error, result) => {
            if(error){
                next(error);
            }
            else{
                res.json(result);
            }
        }
    )
});

任何帮助将不胜感激。我只是对为什么我没有收到错误或任何东西感到困惑。

【问题讨论】:

    标签: reactjs express async-await fetch


    【解决方案1】:

    POST 失败的原因是您的 express 脚本正在寻找 GET,而不是 POST。如果你把它改成如下:

    interestRouter.post('/:university', (req, res, next) => {...
    

    然后就可以在req.body中看到POST的正文了。

    【讨论】:

      猜你喜欢
      • 2021-11-16
      • 2019-02-06
      • 2020-12-27
      • 2020-12-03
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      • 1970-01-01
      相关资源
      最近更新 更多