【问题标题】:I'm having problems using fetch() and can't fetch data我在使用 fetch() 时遇到问题,无法获取数据
【发布时间】:2020-06-11 04:34:33
【问题描述】:

我正在尝试在我的网站上实现 Googles reCaptchaV3,但在使用 fetch() 函数时遇到了问题。 所以这是我到目前为止得到的代码:

function sendData(name, email, captcha) {

    const info = JSON.stringify({
        name: name,
        email: email,
        captcha: captcha
    });

    fetch('/verifycontact', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'mode': 'cors'
        },
        body: info
    })
    .then(res => { 

        alert(JSON.stringify(res));

        res.json()})
    .then(data => {
        alert('msg: ' + data.msg + ', score:' + data.score);
    }) 
}

我尝试警告或 console.log() info 对象,它在第一个 then.() 之前执行 console.log(),当我尝试 console.log() 或警告 res 对象它只是返回空,如下所示:

{}

我缺少代码中的某些内容吗?也许是标题? 在我的服务器上,我正在尝试 console.log(req.body),但我得到了相同的结果,它是 empty。我的 **body 对象与此一起到达我的服务器:

{ success: false, 'error-codes': [ 'invalid-input-response' ] }

【问题讨论】:

    标签: javascript json fetch recaptcha captcha


    【解决方案1】:

    我发现了问题。我需要使用 bodyParser 来使正文正确解析。

    我必须将此中间件快速添加到我的路由器中。这是 bodyParser 配置代码:

    router.use(bodyParser.json({
        verify: (req, res, buf) => {
            req.rawBody = buf;
        }
    }));
    

    这是我必须放在路由上的中间件:

    bodyParser.raw({ type: 'application/json' })
    

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      • 2020-12-11
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多