ERR EMPTY RESPONSE - node.js

I am trying to add a contact form that will send to a dedicated gmail account. I have got the contact form working independently but when I try and add it to my working project it does not work and the error I get is:
Cannot POST /api/send
The project is a MERN stack. Below is the mailer.js middleware:
import nodemailer from 'nodemailer'
import config from '../config'
const transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 587,
auth: {
user: process.env.username,
pass: process.env.password,
}
});
const send = ({ email, name, text }) => {
const from = name && email ? `${name} <${email}>` : `${name || email}`
const message = {
from,
to: 'react.nodemailer#gmail.com',
subject: `New message from ${from} at creating-contact-forms-with-nodemailer-and-react`,
text,
replyTo: from
};
return new Promise((resolve, reject) => {
transporter.sendMail(message, (error, info) =>
error ? reject(error) : resolve(info)
)
})
}
export default send
The server.js on the backend is:
const express = require('express');
const connectDB = require('./config/db');
const path = require('path');
// // ********************
// // CONTACT FORM
// // ********************
const cors = require ("cors")
const nodemailer = require("nodemailer")
// // ********************
// // CONTACT FORM
// // ********************
const app = express();
// // Connect Database
connectDB();
// Init Middleware
app.use(express.json());
// // ********************
// // CONTACT FORM
// // ********************
app.use(cors());
app.post('/contact', (req, res) => {
const { email = '', name = '', message = '' } = req.body
mailer({ email, name, text: message }).then(() => {
console.log(`Sent the message "${message}" from <${name}> ${email}.`);
res.redirect('/#success');
}).catch((error) => {
console.log(`Failed to send the message "${message}" from <${name}> ${email} with the error ${error && error.message}`);
res.redirect('/#error');
})
})
// // ********************
// // CONTACT FORM
// // ********************
// Define Routes
app.use('/api/users', require('./routes/api/users'));
app.use('/api/auth', require('./routes/api/auth'));
app.use('/api/profile', require('./routes/api/profile'));
app.use('/api/posts', require('./routes/api/posts'));
app.use('/api/send', require('./routes/api/send'));
// Serve static assets in production
if (process.env.NODE_ENV === 'production') {
// Set static folder
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
The contact form is:
import React, { Component } from "react";
import axios from "axios";
class ContactForm extends Component {
constructor() {
super();
this.state = {
name: "",
email: "",
message: "",
status: "Submit"
};
}
handleSubmit(event) {
event.preventDefault();
this.setState({ status: "Sending" });
axios({
method: "POST",
url: "api/send",
data: this.state,
}).then((response) => {
if (response.data.status === "sent") {
alert("Message Sent");
this.setState({ name: "", email: "", message: "", status: "Submit" });
} else if (response.data.status === "failed") {
alert("Message Failed");
}
});
}
handleChange(event) {
const field = event.target.id;
if (field === "name") {
this.setState({ name: event.target.value });
} else if (field === "email") {
this.setState({ email: event.target.value });
} else if (field === "message") {
this.setState({ message: event.target.value });
}
}
This is the api POST route.
var express = require('express');
var config = require('config');
var router = express.Router();
var cors = require('cors');
// #route POST api/send
// #desc Send email on contact page
// #access Public
router.post('/api/send',(req, res, next ) => {
var name = req.body.name
var email = req.body.email
var subject = req.body.subject
var message = req.body.message
var content = `
name: ${name} \n
email: ${email} \n
subject: ${subject} \n
message: ${message} `
var post = {
from: name,
subject: subject,
text: content
}
});
module.exports = router;
I have been trying to debug this for a week or so. I am currently trying to find out why the POST route is not working.
The error codes I have got are 500 internal server error and 404 not found. The url it will be going to is http://localhost:5000/api/send

Change
router.post('/api/send',(req, res, next )
to
router.post('/',(req, res, next )
In your express app your already have.
app.use('/api/send', require('./routes/api/send'));
Thus, for all "/api/send" we will look in the file './routes/api/send'.
The way you defined it you will have to query it like http://localhost:5000/api/send/api/send.
You will have
router.post('/',(req, res, next ) => {
var name = req.body.name
var email = req.body.email
var subject = req.body.subject
var message = req.body.message
var content = `
name: ${name} \n
email: ${email} \n
subject: ${subject} \n
message: ${message} `
var post = {
from: name,
subject: subject,
text: content
}
});
module.exports = router;
Also how about moving routes to its own file. i.e in server have
app.use(require('./routes/api'));
And in ./routes/api/index.js have the definitions there. i.e
const express = require('express');
const router = express.Router();
router.use('/api/send', require('./send'));
module.exports = router;

You can directly register the route on the express app like below,
app.post('/api/send',function(){
//..send code
//nodemailer.send("blabla")
});
instead of registering routes both on app and router.

Related

How to store the contents of the request body correctly in Express middleware of POST request

I have a middleware in my React Express project that stores a new user that is created as follows:
const uuid = require('uuid/v4')
const HttpError = require('../models/http-error')
let DUMMY_USERS = [
{
id: 'u1',
name: 'tanaka',
email: 'test#test.com',
password: 'test'
}
]
const signup = (req, res, next) => {
const { name, email, password } = req.body;
const users = DUMMY_USERS
const hasUser = DUMMY_USERS.find(u => u.email === email);
console.log('hasUser ->',hasUser)
if (hasUser) {
throw new HttpError('Could not create user, email already exists.', 422);
}
const createdUser = {
id: uuid(),
name,
email,
password
};
users.push(createdUser);
res.status(201).json({user: createdUser});
};
The middleware is registered on the express Router object as follows:
router.post('/signup', usersControllers.signup)
When I save a new user through Postman by hitting the endpoint http://localhost:5000/api/users/signup with the following body:
{
"name":"test",
"email":"test#email.com",
"password":"test",
}
the body that is saved is as follows:
{
"user": {
"id": "e8a4fe92-0ff1-452e-ba3f-4145289b26d7"
}
}
and when I log the createdUser object, I get undefined values for name, email and password. Why are these destructured values being set to undefined?
Updated to show app.use(express.json()) to parse response body before registering middleware:
The signup middleware is exported into usersRoutes which is registered in app.js below.
const express = require('express')
const HttpError = require('./models/http-error')
const placesRoutes = require('./routes/places-routes')
const usersRoutes = require('./routes/users-routes')
const app = express()
app.use(express.json())
app.use('/api/places', placesRoutes)
app.use('/api/users', usersRoutes)
// middleware to handle unsupported routes
app.use((req, res, next) => {
const error = new HttpError('Could not find this route.', 404)
throw error // could call it as next(error) if this were in asynchronous code eg. communication with the database
})
//error handling middleware
app.use((error, req, res, next) => {
if (res.headersSent) {
return next(error)
}
res.status(error.code || 500)
res.json({message: error.message || 'An unknown error occured!'})
})
app.listen(5000)

Fetch API giving Network request failed Expo App Nodejs

I have written an API in Nodejs which helps in reset password using Mysql database.It is working fine in Postman.I have called this API in Expo IOS App.But I am getting Network request failed error. Below is the Node js program:
app.js:
var express = require('express');
var path = require('path');
var connection = require('./database.js');
var nodemailer = require('nodemailer');
const bcrypt = require("bcryptjs")
var randtoken = require('rand-token');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var flash = require('express-flash');
var session = require('express-session');
var bodyParser = require('body-parser');
const createError = require('http-errors');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
var connection = require('./database.js');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
//send email
function sendEmail(email, token) {
var email = email;
var token = token;
var mail = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'c***********#gmail.com', // Your email id
pass: '**********' // Your password
}
});
var mailOptions = {
from: 'poornima#abccompany.com',
to: email,
subject: 'Reset Password Link - ABCCompany.com',
html: '<p>You requested for reset password, kindly use this link to reset
your password</p>'
};
mail.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(1)
} else {
console.log(0)
}
});
}
app.post('/reset-password-email', function(req, res, next) {
var email = req.body.email;
console.log('email from api '+email);
connection.query('SELECT * FROM JTGDB.UserInfo WHERE email ="' + email + '"',
function(err, result) {
if (err) throw err;
var type = ''
var msg = ''
console.log(result[0]);
if (result[0].Email.length > 0) {
var token = randtoken.generate(20);
var sent = sendEmail(email, token);
if (sent != '0') {
var data = {
token: token
}
connection.query('UPDATE JTGDB.UserInfo SET ? WHERE email ="' + email + '"', data,
function(err, result) {
if(err) throw err
})
type = 'success';
msg = 'The reset password link has been sent to your email address';
} else {
type = 'error';
msg = 'Something goes to wrong. Please try again';
}
} else {
console.log('2');
type = 'error';
msg = 'The Email is not registered with us';
}
res.redirect('/');
});
})
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: '123458cat',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}))
app.use(flash());
app.use('/', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.listen(4000, function () {
console.log('Node app is running on port 4000');
});
module.exports = app;
Below is the IOS App ForgetPassword Screen page:
ForgetPasswordScreen.js:
import React, { Component, Fragment, useState } from "react";
import { View, Text,SafeAreaView, Image, StyleSheet } from "react-native";
import { Formik } from "formik";
import * as Yup from "yup";
import FormInput from "../../components/UI/FormInput";
import FormButton from "../../components/UI/FormButton";
import ErrorMessage from "../../components/UI/ErrorMessage";
import * as authActions from '../../store/actions/auth';
import {useDispatch} from "react-redux";
import Toast from 'react-native-root-toast';
const validationSchema = Yup.object().shape({
email: Yup.string()
.label("Email")
.email("Enter a valid email")
.required("Please enter a registered email"),
});
const ForgotPasswordScreen = props => {
const [isLoading,setIsLoading] = React.useState(false);
const [error, setError] = React.useState('');
const dispatch = useDispatch();
const handlePasswordReset = async (values, actions) => {
const { email } = values;
console.log('email is '+email);
let action
action = authActions.resetpassword(
email
);
setError(null);
setIsLoading(true);
try{
await dispatch(action);
props.navigation.navigate("Login");
} catch (error) {
actions.setFieldError("general", error.message);
}
};
return (
<SafeAreaView>
<View style={styles.emailiconview}>
<Image source={require('../../assets/reset_email.png')} />
</View>
<View style ={styles.instrview1}>
<Text>
Please enter your registered email address below to
</Text>
</View>
<View style={styles.instrview2}>
<Text>receive password reset instruction</Text>
</View>
<View style={styles.emailinputview}>
<Formik
initialValues={{ email: "" }}
onSubmit={(values, actions) => {
handlePasswordReset(values, actions);
}}
validationSchema={validationSchema}
>
{({
handleChange,
values,
handleSubmit,
errors,
isValid,
touched,
handleBlur,
isSubmitting,
}) => (
<Fragment>
<FormInput
name="email"
value={values.email}
onChangeText={handleChange("email")}
placeholder="Enter email"
autoCapitalize="none"
iconName="ios-mail"
iconColor="blue"
onBlur={handleBlur("email")}
/>
<ErrorMessage errorValue={touched.email && errors.email} />
<View style={styles.buttonContainer}>
<FormButton
buttonType="outline"
onPress={handleSubmit}
title="Send Email"
buttonColor="blue"
disabled={!isValid || isSubmitting}
/>
</View>
<ErrorMessage errorValue={errors.general} />
</Fragment>
)}
</Formik>
</View>
</SafeAreaView>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
marginTop: 150,
},
text: {
color: "#333",
fontSize: 24,
marginLeft: 25,
},
buttonContainer: {
margin: 25,
},
emailiconview:{
justifyContent:'center',
alignItems:'center',
top:"30%"
},
instrview1:{
top:'40%',
justifyContent:'center',
alignSelf:'center'
}, instrview2:{
top:'45%',
justifyContent:'center',
alignSelf:'center'
},
emailinputview:{
top:'50%'
}
});
export default ForgotPasswordScreen;
Below is the store auth where I fetch API:
auth.js:
import Device from '../../model/Device';
import AsyncStorage from '#react-native-async-storage/async-storage'
export const FORGOTPASSWORD = 'FORGOTPASSWORD';
export const resetpassword=(email) =>{
console.log(email);
return async dispatch =>{
const response = await fetch(
'http://my_IPV4_Address:4000/reset-password-email',
{
method: 'POST',
header: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email
})
}
);
const resData = await response.text();
console.log(resData);
dispatch({type:FORGOTPASSWORD});
};
}
After running this I am getting the below error in Expo:
Network request failed
It is taking email, but not hitting the api.
email is cpoornima.1987#gmail.com
Email id to API cpoornima.1987#gmail.com
I am getting below error in NodeJs:
email from api undefined
undefined
I have added
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
to the Info.plist. I am just checking in IOS Simulator attached to Expo App. How to get through this?
Below is the auth.js fetch API which is working good.As soon as I press Send Email button, an email is going to provided email id for reset password using real Iphone device.
auth.js:
import Device from '../../model/Device';
import AsyncStorage from '#react-native-async-storage/async-storage'
export const FORGOTPASSWORD = 'FORGOTPASSWORD';
export const resetpassword=(email) =>{
const formData = new FormData();
formData.append('email',email);
console.log('Email id to API '+email);
return async dispatch =>{
fetch('http://My_IPV4_Address:4000/reset-password-email',
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body:JSON.stringify({
email: email,
}),
})
.then(res => res.text())
.then(
(signupresult) =>{
}).catch(err =>{
console.log(err);
})
dispatch({type:FORGOTPASSWORD});
};
}

Trying to run a node-express server to send emails and getting infinte loop

I am trying to run the server in the above title,
and I seem to get an infinite loop with the server restarting itself every second.
Please help and tell me what I am doing wrong I am new to node-express.
const express = require('express');
const app = express();
const router = express.Router();
const nodemailer = require('nodemailer');
const sendGridTransport = require('nodemailer-sendgrid-transport');
const { SENDGRID_API } = require('./config/keys');
// const PORT = process.env.PORT || 5000;
app.use(express.json());
const transporter = nodemailer.createTransport(
sendGridTransport({
auth: {
api_key:
'hidden',
},
})
);
const postMail = router.post('/send', (req, res) => {
const { data, ingredients, price } = req.body;
transporter
.sendMail({
to: 'hidden#hidden.com',
from: 'hidden#hidden.com',
subject: `הזמנה מ:${data.fullName}`,
html: `<h3>שלום יש לך הזמנה חדשה !</h3>
<p>פרטי משלוח:</p>
<p>שם:${data.fullName}</p>
<p>עיר:${data.city}</p>
<p>רחוב:${data.street}</p>
<p>טלפון:${data.phone}
<br></br>
<p>פרטי הזמנה:</p>
<p>כמות בשר:${ingredients.meat}</p>
<p>כמות פסטרמה:${ingredients.pastrama}</p>
<p>כמות סלט:${ingredients.salad}</p>
<br></br>
<p>סה"כ לתשלום:${price}</p>
<p>צורת תשלום:${data.checkbox ? 'מזומן' : 'ביט'}`,
})
.then(resp => {
res.json({ resp });
})
.catch(err => {
console.log(err);
});
});
app.use(postMail);
app.listen(3001);
seems like error is not properly processed by expressjs framework
try
const postMail = router.post('/send', (req, res, next) => { // add `next` here!
const { data, ingredients, price } = req.body;
return transporter
.sendMail({
to: 'hidden#hidden.com',
from: 'hidden#hidden.com',
subject: `הזמנה מ:${data.fullName}`,
html: `<h3>שלום יש לך הזמנה חדשה !</h3>
<p>פרטי משלוח:</p>
<p>שם:${data.fullName}</p>
<p>עיר:${data.city}</p>
<p>רחוב:${data.street}</p>
<p>טלפון:${data.phone}
<br></br>
<p>פרטי הזמנה:</p>
<p>כמות בשר:${ingredients.meat}</p>
<p>כמות פסטרמה:${ingredients.pastrama}</p>
<p>כמות סלט:${ingredients.salad}</p>
<br></br>
<p>סה"כ לתשלום:${price}</p>
<p>צורת תשלום:${data.checkbox ? 'מזומן' : 'ביט'}`,
})
.then(resp => {
res.json({ resp });
})
.catch(next); // change from console.error HERE !!!
});
See https://expressjs.com/en/guide/error-handling.html

Send route not being found,

I am trying to use nodemailer to send an email from the contact page. I have built the site with a MERN stack. All the other routes work perfectly fine. I can setup a new user, write a post and login an existing user. The only part where the routes break is when the mail is sent on the contact page.
Below is the middleware:
const app = express();
// Connect Database
connectDB();
// Init Middleware
app.use(express.json());
// Define Routes
app.use('/api/users', require('./routes/api/users'));
app.use('/api/auth', require('./routes/api/auth'));
app.use('/api/profile', require('./routes/api/profile'));
app.use('/api/posts', require('./routes/api/posts'));
app.use('/api/send', require('./routes/api/send'));
Below is the send route:
var express = require('express');
var config = require('config');
var router = express.Router();
var nodemailer = require('nodemailer');
var cors = require('cors');
// #route POST api/send
// #desc Send email on contact page
// #access Public
router.post('/send',(req, res ) => {
var name = req.body.name
var email = req.body.email
var subject = req.body.subject
var message = req.body.message
var content = `
name: ${name} \n
email: ${email} \n
subject: ${subject} \n
message: ${message} `
var mail = {
from: name,
to: receiver, // receiver email,
subject: subject,
text: content
}
transporter.sendMail(mail, (err, data) => {
if (err) {
res.json({
status: 'fail'
})
} else {
res.json({
status: 'success'
})
}
})
});
module.exports = router;
I get a 404 error when I submit the form on contact page. Below is the contact page:
const ContactForm = () => {
const [state, setState] = useState({
name: '',
email: '',
subject: '',
message: ''
});
const [result, setResult] = useState(null);
const sendEmail = event => {
event.preventDefault();
axios
.post('/send', { ...state })
.then(response => {
setResult(response.data);
setState({
name: '',
email: '',
subject: '',
message: ''
});
})
.catch(() => {
setResult({
success: false,
message: 'Something went wrong. Try again later'
});
});
};
const onInputChange = event => {
const { name, value } = event.target;
setState({
...state,
[name]: value
});
};
This is my handler:
const nodemailer = require ('nodemailer');
nodemailer.createTransport({
host: "smtp.gmail.com", //replace with your email provider
port: 587,
auth: {
user: process.env.email,
pass: process.env.password
}
});
// verify connection configuration
transporter.verify(function(error, success) {
if (error) {
console.log("error at mail send");
} else {
console.log("Server is ready to take the messages");
}
});
module.exports = transporter
To debug I have tried to change the POST route to
(req, res, next)
(req, res, send)
It seems like you missing transpoter object.
You need to create it with nodemailer.createTranspot
const transpoter = nodemailer.createTranspot({
service: 'gmail',
auth: {
user: 'sender#gmail.com',
pass: 'password'
}
})
then try it.
This has been solved by:
Moving the transporter to the send route
The route that the server is using was api/send/send on the POST route it should be /

Sendgrid with Nodejs backend

I am trying to use SendGrid Mail service to send mail and it throw error 400 in the nodejs server.
Is this from Sendgrid or frontend?
I also got the content in the quill rich text editor, because I'm using it.
Every time I get "BAD REQUEST" in the server, but it's sent like [object null reference].
Mail.js, where I'm creating the function:
// SendGrid
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
// cb means callback for error or success
const sendEmail = (email, subject, content, cb) => {
const msg = {
from: email,
to: 'oabdulazeez70#gmail.com',
cc: 'letayoknow#gmail.com',
subject: subject,
text: content,
// html: content,
};
sgMail
.send(msg)
.then(() => {
console.log('Email sent');
// console.log(cb(null, data));
})
.catch((error) => {
console.error(error);
// console.log(cb(error, null));
});
};
module.exports = sendEmail;
index.js //server (backend)
const express = require('express');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const cors = require('cors');
const path = require('path');
const dotenv = require('dotenv');
const app = express();
dotenv.config({ path: './config/config.env' });
// bring in SendEmail
const sendMail = require('./mail');
// View engine setup
app.engine('handlebars', exphbs({ defaultLayout: false }));
app.set('view engine', 'handlebars');
// Static folder
app.use('/public', express.static(path.join(__dirname, 'public')));
// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'contact.html'));
// res.sendFile('contact.html', { root: '.' });
});
//old key
//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
app.post('/send', (req, res) => {
const { subject, to, content, email } = sendMail;
sendMail(email, to, subject, content, () => {
if (err) {
console.error(err.ResponseError);
res.status(400).json({ message: 'Internal Error' });
} else if (res.status(500)) {
console.log('Error Something happned!');
} else {
console.log(data);
res.json({ message: 'Message Sent' });
}
});
console.log(req.body);
});
// Setting PORT from .env
const PORT = process.env.PORT || 5000;
// console.log(process.env);
app.listen(PORT, () => console.log(`Server Started on ${PORT}`));
app.js (frontend)
const getIds = (id) => {
return document.getElementById(id);
};
const form = document.querySelector('#form');
form.addEventListener('submit', (e) => {
e.preventDefault();
const from = getIds('from').value;
const subject = getIds('subject').value;
const emailFormat = quill.root.innerHTML;
const content = (getIds('content').value = emailFormat);
const data = {
from,
subject,
content,
};
axios
.post('/send', data, {
headers: {
'Content-Type': 'application/json',
},
})
.then((res) => {
form.reset();
quill.setContents([{ insert: '\n' }]);
M.toast({ html: 'Email Sent!!' });
console.log(res);
})
.catch((err) => console.log(err));
});
You can use #sendgrid/mail NPM module.
import sgMail from '#sendgrid/mail';
const setApiKey = () => sgMail.setApiKey(process.env.SENDGRID_API_KEY);
export const sendEmail = ({
emailTo, data, emailFrom
}) => {
return new Promise(async (resolve, reject) => {
try {
setApiKey();
const msg = {
to: [emailTo],
from: emailFrom, // Use the email address or domain you verified above
subject: 'Sending with Twilio SendGrid is Fun',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
const result = await sgMail.send(msg);
resolve(result);
} catch (_e) {
console.log('Error in sendEmail: ', _e.response.body);
reject(_e.response.body);
}
});
};
For your case use this one
import sgMail from '#sendgrid/mail';
const setApiKey = () => sgMail.setApiKey(process.env.SENDGRID_API_KEY);
export const sendEmail = (email, subject, content) => {
return new Promise(async (resolve, reject) => {
try {
setApiKey();
const msg = {
from: email,
to: 'oabdulazeez70#gmail.com',
cc: 'letayoknow#gmail.com',
subject: subject,
text: content,
};
const result = await sgMail.send(msg);
resolve(result);
} catch (_e) {
console.log('Error in sendEmail: ', _e.response.body);
reject(_e.response.body);
}
});
};
app.post('/send', (req, res) => {
try {
const { email, subject, content } = req.body;
await sendMail(email, subject, content);
res.json({ message: 'Message Sent' });
} catch (error) {
res.status(400).json({ message: 'Something went wrong' });
}
console.log(req.body);
});

Resources