Search code examples
node.jsfetchsendgridhttp-status-code-400bad-request

SendGrid using NodeJS with Fetch - 400 Bad Request


I'm getting a 400 Bad Request from the SendGrid Web API when I'm trying to send the following request to SendGrid via fetch with NodeJS:

 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)

The request works in Postman using the same payload.


Solution

  • Example from the node-fetch documentation seems to indicate that you need to use JSON.stringify() on the body.

    Quote:

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

    From: https://github.com/bitinn/node-fetch#usage