简体   繁体   中英

SendGrid with Node.js and express

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: "...@...com",
        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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM