【问题标题】:Send mail with Nuxt trough Sendgrid使用 Nuxt 槽 Sendgrid 发送邮件
【发布时间】:2018-11-30 14:13:45
【问题描述】:

我有一个简单的 vuetify 联系表格,我想通过电子邮件发送此表格。 我尝试使用method 发送电子邮件,但它不起作用,因为它在客户端。所以我遇到了 CORS 问题。

这是我的代码:

async send() {
  if (this.$refs.form.validate()) {
    try {
      const sgMail = require("@sendgrid/mail");
      sgMail.setApiKey(process.env.SENDGRID_API_KEY);
      const msg = {
        to: "test@example.com",
        from: "me@mydomain.com",
        subject: "Sending with SendGrid is Fun",
        text: "and easy to do anywhere, even with Node.js",
        html: "<strong>and easy to do anywhere, even with Node.js</strong>"
      };
      sgMail.send(msg);
    }
  }
}

是否需要 Express(或其他后端)?有没有办法使用中间件让它工作?

编辑

显然,这是不可能的:https://github.com/sendgrid/sendgrid-nodejs/issues/730

【问题讨论】:

    标签: sendgrid nuxt.js


    【解决方案1】:

    Sendgrid 的 CORS 策略不允许您从浏览器使用他们的 API(“Access-Control-Allow-Origin”标头的值为“https://sendgrid.api-docs.io)。 p>

    引用自https://sendgrid.com/docs/for-developers/sending-email/cors/

    在 SendGrid 的案例中,我们不允许我们的客户对我们的 v3/mail/send 端点进行基于浏览器的调用。 (...) 您可以创建一个基于服务器的应用程序,这将保护您的 API 密钥不被公开。可以实现 NodeJS、PHP、Ruby、Python、C#、Go 和 Java 等语言,以便从锁定的服务器环境的安全性中调用 API。

    您必须从服务器发送电子邮件,这是一件好事,因为否则您的 API 密钥会被浏览器公开。

    如果您在 SSR 模式下使用 Nuxt(运行 Node),我想您可以创建一个“服务器中间件”(https://nuxtjs.org/api/configuration-servermiddleware),例如使用类似“/api/mail”的路径,它将发送电子邮件。

    如果您使用 nuxt-generate 创建静态站点,则可以使用“功能即服务”,例如“https://webtask.io/”来创建小节点脚本;您可以通过客户端的 url 触发发送电子邮件。

    【讨论】:

    • 这里是消息:Access to fetch at 'https://api.sendgrid.com/v3/mail/send' from origin 'https://domain.herokuapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'https://sendgrid.api-docs.io' that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
    • 好吧,他们的 CORS 策略不允许浏览器调用他们的 API(除非你在“sendgrid.api-docs.io”域上)......你必须从你的服务器发送电子邮件,这是最好的让您的 API 密钥保密的方法
    猜你喜欢
    • 1970-01-01
    • 2016-09-01
    • 2018-11-08
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多