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.