2017-06-06 120 views
0

我正在localhost(在一個靜態React網絡應用程序內)和表單提交,我想通過我的聯繫表格發送電子郵件。所以我張貼到mailgun API,像這樣:通過mailgun API發送郵件只使用客戶端AJAX請求

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等似乎沒有任何工作

+0

你知道了嗎?我以爲你只能從服務器發送 – timh

+0

@timh沒有你必須使用服務器 –

回答

1

不知道如果我回答是爲時已晚,但你可以試試這個:

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文檔指出它接受請求參數而不是請求正文,因此在您使用的Axios中應該使用params而不是數據

對於基本認證通過Mailgun需要,愛可信也提供了一個更好的方式來做到這一點,那就是提供一個權威性的對象(參見上面的代碼)

您可以參考以下鏈接瞭解更多詳情

希望這有助於!

相關問題