reactjs 如何使用mailchimp API摆脱CORS错误?

az31mfrm  于 2023-01-30  发布在  React
关注(0)|答案(2)|浏览(110)

如何使用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){}

这是使用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}`,
        },
});

但是得到了同样的问题!

vzgqcmou

vzgqcmou1#

我通过从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 });
}

然后转到您的客户端并获取此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,
          },
        }),
  });

就是这样

7cwmlq89

7cwmlq892#

您的回答帮助@Almo。谢谢:)
我想添加一些东西,但无法添加。缺少的一个修复是您忘记导出API组件。例如,export default async (req, res) => {或命名函数export default async function handler(req, res) {

相关问题