带有用于电子邮件的自定义 Sendgrid 控制器代码的 Strapi Beta

Strapi Beta with custom Sendgrid Controller code for email

Strapi beta 的结构改变了插件的构建方式,删除了 /plugins 目录,插件现在保存在 /node_modules 目录中。我正在尝试编写一些自定义代码以在下订单后发送确认电子邮件。在之前版本的 Strapi 中,邮件插件目录在这里:

/server/plugins/email/controllers

在此目录中,编写了以下代码,该代码在 SEND 控制器中处于 alpha 状态:

我们评论出来: // await.strapi.plugins.email.services.send(options, config);

然后此代码用于曾经存在的电子邮件控制器 module.exports 内的 SEND 控制器...

let options = ctx.request.body;

   try {
   // send email to user
   await strapi.plugins['email'].services.email.send({
      to: options.to,
      from: 'test@example.com',
      subject: options.subject,
      text: options.text,
      html: options.html
   })
} catch (err) {
   return ctx.badRequest(null, err);
}

   // Send 200 'ok;
   ctx.send({});

好的,那是服务器端的 Strapi Send 控制器......现在在客户端承诺订单 returns 后,我们触发另一个承诺,发送确认电子邮件,点击 Strapi API:

await.strapi.request('POST', '/email', { 
   data: {
      to: confirmationEmailAdress,
      subject: "Order Confirmation',
      text: 'Your order has been processed',
      html: '<b>Expect your stuff to arrive broken. Thanks.</b>'
   }
});

简而言之,现在的问题是 Strapi 的架构发生了变化,不确定将我的服务器代码放在哪里,还有 API url 调用以触发电子邮件.我在 Strapi 中设置了带有 API 密钥、权限的 SendGrid,一切都很好,只是一个问题,现在 Beta 架构已经从 alpha 改变了,把这段代码放在哪里合适?

* 更新代码 *

根据 Jim 的建议,我现在已经在 /extensions 文件夹中创建了一个电子邮件控制器,如下所示:

/server/extensions/email/controllers/Email.js

Email.js

'use strict';

module.exports = {

  send: async (ctx) => {
    let options = ctx.request.body;

    try {
      //Send email to the user
      await strapi.plugins['email'].services.email.send({
        to: options.to,
        from: 'test@example.com',
        subject: options.subject,
        text: options.text,
        html: options.html
      });
    } catch (err) {
      return ctx.badRequest(null, err);
    }
  }
}

现在,在客户端中,我使用 React 的承诺来调用我们的电子邮件扩展,如下所示:

await strapi.request('POST', '/email', {
        data: {
          to: confirmationEmailAddress,
          subject: `Order Confirmation - South of Sleep ${new Date(Date.now())}`,
          text: 'Your order has been processed',
          html: '<bold>Except your stuff to be broken upon arriving</bold>'
        }
      });

有效!电子邮件是从 Strapi 发送的,我看到控制器中的信息是电子邮件的一部分。问题?

客户端中的承诺是 try/catch 的一部分,并且在电子邮件被触发后它 returns 404,因为它找不到 /email 作为路由。所以,我不明白为什么它能正常工作并找到电子邮件的扩展控制器,触发电子邮件但返回 404 路由。

我错误地从客户端调用扩展控制器。

现在您必须按照自定义文档进行操作。 这是文档 https://strapi.io/documentation/3.0.0-beta.x/concepts/customization.html#plugin-extensions

  • 您必须按照要更新的文件路径创建文件。
  • 然后你只复制你需要的函数。
  • 最后添加电子邮件服务电话。