简体   繁体   English

React和NodeJS:如何从服务器向客户端发送数据?

[英]React and NodeJS: How can i send data from server to client?

I want to send responsed data from server to client. 我想将响应的数据从服务器发送到客户端。 I use a NodeJS Server with NextJS and React. 我将NodeJS服务器与NextJS和React一起使用。

I use this function on the server: 我在服务器上使用此功能:

function addEmailToMailChimp(email) {
    var request = require("request");
    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, function (error, response, body) {
        //if (error) throw new Error(error);
        return body; //return the body Value
    });
    return request();
}

In the nested request() function i want to return the body value... The function will be run from this point: 在嵌套的request()函数中,我想返回主体值...该函数将从此时开始运行:

server.post('/', (req, res) => {
            var MailChimpError = addEmailToMailChimp(req.body.email);
            console.log(MailChimpError); 
            res.send(MailChimpError); //send data to client
            res.end("success!");
        })

i try to save the return body Value inside the variable MailChimpError and try to show this variable in the Server Console. 我尝试将返回正文值保存在变量MailChimpError并尝试在服务器控制台中显示此变量。 But it doesn't work. 但这是行不通的。 That's the first problem. 那是第一个问题。

The second problem: I want to send the MailChimpError variable to the Client to show some error, if exits. 第二个问题:如果退出,我想将MailChimpError变量发送给客户端以显示一些错误。 On the Server i use the function res.send(MailChimpError) . 在服务器上,我使用功能res.send(MailChimpError) My handleSubmit() function on the Client Side looks like this: 我在客户端上的handleSubmit()函数如下所示:

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.body)) //display the body value from server
      }

How can i do that? 我怎样才能做到这一点? I have little experience in Node.js environments. 我在Node.js环境中经验不足。 I would be very grateful if you could show me concrete solutions. 如果您能给我具体解决方案,我将不胜感激。 Thank you for your replies. 谢谢您的回复。

Below is the right way to use the response from the function addEmailToMailChimp as it's an asynchronous function. 下面是使用来自addEmailToMailChimp函数的响应的正确方法,因为它是异步函数。 For more examples, you can refer 有关更多示例,您可以参考

I changed addEmailToMailChimp to accept a callback which I then passed to request as the second parameter which will be executed once the async operation has been finished. 我将addEmailToMailChimp更改为接受callback ,然后将该callback传递给request作为第二个参数,该参数将在异步操作完成后执行。

var request = require("request");
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);
}

In your server.js file 在您的server.js文件中

server.post('/', (req, res) => {
    addEmailToMailChimp(req.body.email, (error, response, body) => {
        // This is the callback function which is passed to `addEmailToMailChimp`
        if(error){
            console.log('error', error);
            res.status(500).send({msg: 'Sorry, something went wrong :('})
        }
        else{
            res.status(200).send(response); //send data to client
        }

    });
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM