2017-02-22 87 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