【发布时间】:2019-03-05 05:48:20
【问题描述】:
我想将响应的数据从服务器发送到客户端。我使用带有 NextJS 和 React 的 NodeJS 服务器。
我在服务器上使用这个功能:
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();
}
在嵌套的request() 函数中,我想返回正文值...
该函数将从这一点开始运行:
server.post('/', (req, res) => {
var MailChimpError = addEmailToMailChimp(req.body.email);
console.log(MailChimpError);
res.send(MailChimpError); //send data to client
res.end("success!");
})
我尝试将返回正文值保存在变量MailChimpError 中,并尝试在服务器控制台中显示此变量。但它不起作用。这是第一个问题。
第二个问题:如果退出,我想将MailChimpError 变量发送给客户端以显示一些错误。在服务器上,我使用函数res.send(MailChimpError)。我在客户端的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
}
我该怎么做?我在 Node.js 环境中几乎没有经验。如果您能向我展示具体的解决方案,我将不胜感激。感谢您的回复。
【问题讨论】:
-
您期望变量
MailChimpError中的值是多少?是来自request(options, function (error, response, body)的返回值吗? -
^^ ...而且它不是您从传递给
request的回调中返回的值。
标签: javascript json node.js reactjs next.js