2017-02-22 86 views
0

我想使用sendgrid V3 api將我們的用戶添加到郵件列表中。我構建了以下的Ajax請求來擊中他們的API,但我一直得到bad request錯誤。我省略了xhr.setRequestHeader,但是我確實有一個有效的API密鑰並且它可以工作,因爲當它被省略時,它將返回一個403.現在,我只得到了400個錯誤的請求主體。我已經讓我的請求身體看起來很像他們的例子,我仍然堅持。 Example request body from their websiteSendgrid v3 api返回不良請求

var sendgridData = 
    [ 
    { 
     "marketing_emails": 0, 
     "weekly_emails": 0, 
     "email": userProfile.email, 
     "first_name": "foo", 
     "last_name": 'bar', 
     "userid": 2, 
    } 
    ] 
$.ajax({ 
    method: 'POST', 
    url: 'https://api.sendgrid.com/v3/contactdb/recipients', 
    data: sendgridData, 
    dataType: 'json', 
    contentType: 'application/json', 
}, 
success: 
function(res) 
{ 
    console.log(1, res) 

    Modal.close(); 
    }, 
    error: 
    function(e) 
    { 
     Modal.close(); 
     console.log(1,e); 
    } 
}) 

回答

1

更新,其中的代碼工作樣品和working jsfiddle

var apiKey = 'Bearer [API KEY HERE]' 

var sendgridData = [ 
    { 
    "marketing_emails": 0, 
    "weekly_emails": 0, 
    "email": '[email protected]', 
    "first_name": "foo", 
    "last_name": 'bar', 
    "userid": 2, 
    } 
] 

$.ajax({ 
    method: 'POST', 
    url: 'https://api.sendgrid.com/v3/contactdb/recipients', 
    data: JSON.stringify(sendgridData), 
    dataType: 'json', 
    headers: { 'Authorization': apiKey }, 
    crossDomain: true 
}) 
.done(function(res) { 
    console.log(1, res) 
}) 
.fail(function (e) { 
    console.log(2, e.status, e.responseText) 
}) 

讓我們來看看你正在做的請求,並從那裏。您正在向API發送請求併發送一些數據,如Content-Type: application/json;。 API正在響應400 Bad Request。 API返回400的原因是因爲您發送服務器不喜歡或不能讀取/解析的請求。

還有一些其他的東西你的代碼錯誤,以及:

  1. 對V3聯繫人API端點是https://api.sendgrid.com/v3/contactdb/recipients
  2. 你不會沿着任何認證頭髮送的。你很可能無法做到這一點,因爲這將是一個巨大的安全隱患,暴露你的API密鑰Sendgrid 到世界
+0

感謝您對布蘭登的迴應。 「聯繫人」是一個錯字。在我的代碼中,它一直是'/ contactdb /',並且錯誤依然存在。我也有一個密鑰的授權,但由於顯而易見的原因,將它放在我的問題主體之外。任何其他想法? –

+0

我能夠重現這個問題並且有一段代碼,我會用它更新我的答案。 – brandon927