【发布时间】: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