SendGrid使用NodeJS和Fetch - 400 Bad Request

时间:2017-08-10 12:21:18

标签: node.js fetch sendgrid http-status-code-400 bad-request

当我尝试通过NodeJS提取向SendGrid发送以下请求时,我从SendGrid Web API收到400 Bad Request:

 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中工作。

1 个答案:

答案 0 :(得分:0)

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

引用:

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