SendGrid 使用 NodeJS 和 Fetch - 400 错误请求

SendGrid using NodeJS with Fetch - 400 Bad Request

当我尝试通过使用 NodeJS 获取将以下请求发送到 SendGrid 时,我收到来自 SendGrid Web API 的 400 错误请求:

 var emailBody = {
 "personalizations":[
    {
       "to":[
          {
             "email":"some_email@gmail.com"
          }
       ]
    }
 ],
 "from":{
    "email": "some_email@gmail.com"
 },
 "subject": "Send Grid",
 "content": [
    {
       "type":"text/plain",
      "value": "Send Grid msg"
    }
 ]
};

var emailOptions = {
method: 'POST',
headers: {
  'Authorization': 'Bearer ' + [API_Key],
  'content-type': 'application/json'
},
body: emailBody
 };
fetch(sendGridUrl, emailOptions)

该请求使用相同的负载在 Postman 中工作。

node-fetch 文档中的示例似乎表明您需要在 body 上使用 JSON.stringify()

引用:

var body = { a: 1 };
fetch('http://httpbin.org/post', { 
    method: 'POST',
    body:    JSON.stringify(body),
    headers: { 'Content-Type': 'application/json' },
})
    .then(res => res.json())
    .then(json => console.log(json));

发件人:https://github.com/bitinn/node-fetch#usage