Home > Back-end >  SendGrid with Node.js and express
SendGrid with Node.js and express

Time:08-05

I'm trying to use Sendgrid in Node.js and I'm all new with them.

I used express to build a website and use app.post to get the email address from the form on the website. I do can get the email address but when it supposed to send to email, I received the ResponseError: Bad Request error.

I tried to re-write in different ways but I get the same problem.

This is what I wrote in Node (I hid the apikey and my eamil address), server.js:

const express = require("express")
const bodyParser = require("body-parser")
const sgMail = require("@sendgrid/mail")
sgMail.setApiKey("SG....................SsSwXtdjRE")

const app = express()
app.use(
    bodyParser.urlencoded({
        extended: false
    })
)

app.listen(3000, function(err) {
    if(err) console.error(err);
    console.log("successfully connected")
})

app.get("/", (req, res) => {
    res.sendFile(__dirname   '\\index.html')
})


app.post("/", (req, res) => {
    var email = String(req.body.email)
    console.log(email)

    const msg = {
        to: email,
        from: "[email protected]",
        text: "hello world"
    }    
    console.log(msg)
    
    sgMail.send(msg).then(() => {
        console.log("Email sent successfully")
    }).catch((error) => {
        console.log("Failed")
        console.error(error)
    })
})

The code in html is just a form with POST method and some inputs.

This is the error in the terminal: enter image description here

CodePudding user response:

I see there is body with errors, so you can try to console.log(error.response.body) to check what errors you have. But checking your code I assume it could be:

  1. Missing "subject" field.
  2. Invalid from email. As I remember, it has to match your Sendgrid account or domain you specified there.
  • Related