utopia.co.uk/contact-email-server/app.js

53 lines
1.5 KiB
JavaScript

#!/usr/bin/env node
const express = require("express");
const config = require("./config.js");
// app
const app = express();
// This middleware will parse JSON in the request body
app.use( express.json() );
// set the headers
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
});
// end point for post form
app.post( "/api/contact-details", (req, res) => {
const form = req.body;
return triggerEmail( form, res );
});
// populate params and trigger enail
function triggerEmail( form , res){
try {
// initialize param for template
const params = config.PARAMS( form );
// trigger email
config.AWS_SES.sendEmail( params, ( err, data ) => {
if ( err ) {
console.log(err, err.stack);
} else {
console.log('Email sent successfully:', data);
}
});
// Send an HTTP 200 response with the 'OK' message
res.status(200).send( 'Email Sent' );
}
catch( exception ){
// Send an HTTP 500 response with the 'Email Trigger Failed' message
res.status(500).send( 'Email Trigger Failed' );
}
}
// port #
const PORT = 3005;
// server listen
app.listen(PORT, (error) => {
console.log(`Server is listening on port ${PORT}`);
});