Ali*_*Ali 4 mailchimp cors reactjs next.js mailchimp-api-v3
如何使用mailchimp API处理CORS错误?
这是我使用 mailchimp 包的代码:
import mailchimp from '@mailchimp/mailchimp_marketing'
mailchimp.setConfig({
apiKey: process.env.NEXT_PUBLIC_MAILCHIMP_API_KEY,
server: process.env.NEXT_PUBLIC_MAILCHIMP_DC,
});
try {
const response = await mailchimp.lists.addListMember(process.env.NEXT_PUBLIC_MAILCHIMP_LIST_ID, {
email_address: email,
status: "pending",
});
catch(err){}
Run Code Online (Sandbox Code Playgroud)
这是使用 axios:
const url = `https://${process.env.NEXT_PUBLIC_MAILCHIMP_DC}.api.mailchimp.com/3.0/lists/${process.env.NEXT_PUBLIC_MAILCHIMP_LIST_ID}/members`;
const { data } = await axios.post(url, providedData, {
headers: {
Authorization: `auth ${process.env.NEXT_PUBLIC_MAILCHIMP_API_KEY}`,
},
});
Run Code Online (Sandbox Code Playgroud)
但遇到了同样的问题!
我通过从 nextJS 服务器端调用 Mailchimp API 解决了这个问题。
您所要做的就是转到pages/api
并使用以下代码添加一条路由作为示例(根据您的需要):
import mailchimp from '@mailchimp/mailchimp_marketing';
async function handler(req, res) {
const {email_address, status, merge_fields} = req.body
mailchimp.setConfig({
apiKey: process.env.NEXT_PUBLIC_MAILCHIMP_API_KEY,
server: process.env.NEXT_PUBLIC_MAILCHIMP_DC,
});
try {
await mailchimp.lists.addListMember(
process.env.NEXT_PUBLIC_MAILCHIMP_LIST_ID,
{
email_address,
status,
merge_fields
}
);
} catch (err) {
return res.status(400).send({ error: true })
}
return res.json({ success: true });
}
Run Code Online (Sandbox Code Playgroud)
然后转到您的客户端并获取此 API,如下所示:
const res = await fetch('/api/signup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email_address: email,
status: 'subscribed',
merge_fields: {
FNAME: name,
},
}),
});
Run Code Online (Sandbox Code Playgroud)
就是这样
| 归档时间: |
|
| 查看次数: |
3692 次 |
| 最近记录: |