【问题标题】:React and NodeJS: How can i use received data from Server on Client?React 和 NodeJS:如何在客户端使用从服务器接收到的数据?
【发布时间】:2019-03-05 09:13:01
【问题描述】:

我想在客户端使用从服务器接收到的数据。我使用带有 NextJS 和 React 的 NodeJS 服务器。

我在服务器上使用这个功能:

function addEmailToMailChimp(email, callback) {
    var options = {
        method: 'POST',
        url: 'https://XXX.api.mailchimp.com/3.0/lists/XXX/members',
        headers:
        {
            'Postman-Token': 'XXX',
            'Cache-Control': 'no-cache',
            Authorization: 'Basic XXX',
            'Content-Type': 'application/json'
        },
        body: { email_address: email, status: 'subscribed' },
        json: true
    };
    request(options, callback);
}

函数将从这一点开始运行:

server.post('/', (req, res) => {
            addEmailToMailChimp(req.body.email, (error, response, body) => {
                // This is the callback function which is passed to `addEmailToMailChimp`
                try {
                    var respObj = {}; //Initial response object
                    if (response.statusCode === 200) {
                      respObj = { success: `Subscribed using ${req.body.email}!`, message: JSON.parse(response.body) };
                    } else {
                      respObj = { error: `Error trying to subscribe ${req.body.email}. Please try again.`, message: JSON.parse(response.body) };
                    }
                    res.send(respObj);
                  } catch (err) {
                    var respErrorObj = { error: 'There was an error with your request', message: err.message };
                    res.send(respErrorObj);
                  }
            });
        })

try 方法用于验证电子邮件地址是否可以成功保存到 MailChimp。将向客户端发送适当的消息。

在客户端,我使用这个函数来接收和显示来自服务器的数据:

handleSubmit() {
        const email = this.state.email;
        this.setState({email: ""});
        fetch('/', {
            method: 'POST',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({email:email}),
          }).then(res => {
            if(res.data.success) {
              //If the response from MailChimp is good...
              toaster.success('Subscribed!', res.data.success);
              this.setState({ email: '' });
            } else {
              //Handle the bad MailChimp response...
              toaster.warning('Unable to subscribe!', res.data.error);
            }
          }).catch(error => {
            //This catch block returns an error if Node API returns an error
            toaster.danger('Error. Please try again later.', error.message);
          });
      }

问题:邮件地址在MailChimp上保存成功,但邮件总是显示:'Error. Please try again later.'来自.catch区域。当我从捕获区域记录错误时,我得到了这个:

TypeError: Cannot read property 'success' of undefined

我的错误在哪里?我在 Node.js 环境中几乎没有经验。如果您能向我展示具体的解决方案,我将不胜感激。感谢您的回复。

【问题讨论】:

    标签: javascript node.js reactjs mailchimp-api-v3.0 next.js


    【解决方案1】:

    对于fetch,响应中没有数据属性。您必须致电 res.json() 并返回该承诺。将从那里读取响应正文并对其进行反序列化。

    【讨论】:

    • 谢谢你的回答,我试试fetch.json() 但这不是一个函数,或者你是什么意思?请你告诉我,我需要改变什么
    • 它的res.json()
    • 感谢您的回答,但我仍然收到来自捕获区的错误消息,为什么?
    【解决方案2】:
    handleSubmit() {
            const email = this.state.email;
            this.setState({email: ""});
            fetch('/', {
                method: 'POST',
                headers: {
                  'Accept': 'application/json',
                  'Content-Type': 'application/json'
                },
                body: JSON.stringify({email:email}),
              })
             .then(res => {
                console.log(res); //to make sure the expected object is returned
                if(res.data.success) {
                  //If the response from MailChimp is good...
                  toaster.success('Subscribed!', res.data.success);
                  this.setState({ email: '' });
                } else {
                  //Handle the bad MailChimp response...
                  toaster.warning('Unable to subscribe!', res.data.error);
                }
              }).catch(error => {
                //This catch block returns an error if Node API returns an error
                toaster.danger('Error. Please try again later.', error.message);
              });
          }
    

    【讨论】:

    • 感谢您的回答,但我仍然收到来自捕获区的错误消息,为什么?
    • 您是否获得了您期望的响应的控制台日志?也尝试注释掉 toaster.success 看看这是否是问题
    • 是的,我得到了控制台日志。它告诉我:error: "There was an error with your request"message: "Unexpected token o in JSON at position 1" 这是什么意思?但是电子邮件地址存储在 MailChimp...
    • 那么就不需要 res.json()。我已经在上面删除了它。错误似乎来自后端的 try/catch。为什么不控制台记录响应和正文以查看从 Mailchimp 中返回的内容并查看它可能在哪里引发错误
    【解决方案3】:

    你需要改变两件事:

    1. 调用并等待 res.json() 将响应正文作为 json 对象获取。
    2. 1. 的结果是您可以直接使用的“数据”对象

    handleSubmit() {
        //...
        fetch('/', {
            method: 'POST',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({email:email}),
          })
          .then(res => res.json())
          .then(data => {
            if(data.success) {
              //...
              toaster.success('Subscribed!', data.success);
            } else {
              toaster.warning('Unable to subscribe!', data.error);
            }
          }).catch(error => {
            //...
          });
      }
    

    【讨论】:

      猜你喜欢
      • 2019-03-05
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 2017-05-10
      • 2013-10-25
      • 1970-01-01
      • 2020-09-09
      相关资源
      最近更新 更多