【问题标题】:Sendgrid v3 api returns bad requestSendgrid v3 api 返回错误请求
【发布时间】:2017-02-22 19:39:39
【问题描述】:

我正在尝试使用 sendgrid V3 api 将我们的用户添加到邮件列表。我已经构建了以下 Ajax 请求来访问他们的 API,但我不断收到 bad request 错误。我省略了xhr.setRequestHeader,但我确实有一个有效的 API 密钥并且它可以工作,因为当它被省略时,它返回一个 403。现在,我只得到 400 错误的请求正文。我已经使我的请求正文看起来与他们的示例完全一样,但仍然卡住了。

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);
     }
 })

【问题讨论】:

标签: javascript ajax sendgrid


【解决方案1】:

更新了工作示例代码和working jsfiddle:

var apiKey = 'Bearer [API KEY HERE]'

var sendgridData = [
  {
    "marketing_emails": 0,
    "weekly_emails": 0,
    "email": 'someperson@example.com',
    "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. 您根本没有发送任何身份验证标头。您可能无法在客户端执行此操作,因为这将是一个巨大的安全风险,会将您的 Sendgrid API 密钥暴露给全世界

【讨论】:

  • 感谢布兰登的回复。 “联系人”是一个错字。在我的代码中,一直是/contactdb/,并且错误仍然存​​在。我也有密钥授权,但出于显而易见的原因,我将其排除在我的问题主体之外。还有其他想法吗?
  • 我能够重现该问题并拥有一段工作代码,我将用它更新我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-25
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
相关资源
最近更新 更多