0

I want to send responsed data from server to client. I use a NodeJS Server with NextJS and 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:

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. 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. On the Server i use the function res.send(MailChimpError). My handleSubmit() function on the Client Side looks like this:

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. I would be very grateful if you could show me concrete solutions. Thank you for your replies.

Niklas
  • 1,638
  • 4
  • 19
  • 48

1 Answers1

0

Below is the right way to use the response from the function addEmailToMailChimp as it's an asynchronous function. 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.

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.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
        }

    });
})
Suresh Prajapati
  • 3,991
  • 5
  • 26
  • 38