仅使用客户端ajax请求通过mailgun api发送邮件

问题描述 投票:1回答:1

我正在使用localhost(在静态React Web应用程序内)和表单提交,我想通过我的联系表单发送电子邮件。所以我发布到mailgun api就像这样:

   axios({
      url: 'https://api:[email protected]/v3/somesandboxdomain1c.mailgun.org/messages',
      method: 'post',
      username: 'api',
      password: 'key-somekey',
      data: {
        from: "Excited User <[email protected]>",
        to: "[email protected]",
        subject: "Hello from react app",
        text: "Testing some Mailgun awesomness!"
      },
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        'Authorization': `Basic ${window.btoa('api:key-someapikey')}`
      }
    })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });

但我一直得到这个错误或其中一个变化:

XMLHttpRequest cannot load https://api.mailgun.net/v3/somesandbox.mailgun.org. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

我使用静态Web应用程序,没有服务器通过它发送数据。我已经尝试添加和删除各种标题,如Access-Control-Allow-Headers: Authorization等。似乎没有什么工作

ajax email mailgun axios
1个回答
2
投票

不确定我是否回答太晚,但你可以试试这个:

axios({
    method: 'post',
    url: `${mailgun.baseUrl}/${mailgun.domain}/messages`,
    auth: {
        username: 'api',
        password: mailgun.apiKey
    },
    params: {
        from: 'Awesome Development Team <[email protected]>',
        to: '[email protected]',
        subject: 'Hello',
        text: 'Welcome to the team!'
    }
}).then(
    response => {
        console.log(response)
    },
    reject => {
        console.log(reject)
    }
)

Mailgun文档声明它接受请求参数而不是Request Body,因此在Axios中你应该使用params而不是data。

至于Mailgun所需的Basic Auth,Axios确实提供了一种更好的方法,即提供一个auth对象(参考上面的代码)

您可以参考这些链接以获取更多详细信息

希望这可以帮助!

© www.soinside.com 2019 - 2024. All rights reserved.