How can we deploy nodemailer nodejs app on production server

Viewed 164

I am trying to create the nodejs app using nodemailer packages. I have created the app successfully on my local server and it's working well as I expected. But when I am trying to run on the server then the listing(e.g. http://localhost:5000/ or http://server_ip:5000/ ) URL is not working on the production. I tried with the given below links i.e. they had explained properly and the Hello Word program is running well server.

  1. Packaging a Node.js project as an RPM for CentOS 7
  2. How To Set Up a Node.js Application for Production on Ubuntu 20.04

But the given below code server.js is not working on production.

require('dotenv').config({ path: './.env' });
// require('dotenv').config();
const express = require("express");
const router = express.Router();
const cors = require("cors");
const nodemailer = require("nodemailer");

// const PORT = process.env.PORT || 5000;
// console.log(PORT);

// const app = express();

// console.log(process.env.VALUE);

const app = express();
app.use(cors());
app.use(express.json());
app.use("/", router);
app.listen(5000, () => console.log("Server Running"));

const contactEmail = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: process.env.GMAIL_USERNAME,
    pass: process.env.GMAIL_PASSWORD,
  },
});

contactEmail.verify((error) => {
  if (error) {
    console.log(error);
  } else {
    console.log("Server is ready to send your messages");
  }
});

router.post("/contact", (req, res) => {
  const name = req.body.name;
  const email = req.body.email;
  const message = req.body.message; 
  const mail = {
    from: name,
    to: process.env.SEND_TO_EMAIL,
    subject: 'Messages from website: ' + EmailSubject,
    html: `<p>Name: ${name}</p><p>Email: ${email}</p><p>Message: ${message}</p>`,
  };
  contactEmail.sendMail(mail, (error) => {
    if (error) {
      res.json({ status: "ERROR" });
    } else {
      res.json({ status: "Thanks for your time. Your message has been sent successfully!" });
    }
  });
});

// app.listen(PORT, () => console.log("Server Running"));

I run the above code by command node server on localhost then it's working but on the production, it's not working. Where I did wrong? Is there any mistake in port or hostname that is not declared by me?. my project structure is like

node_modules, .env, package.json, server.js,

Below is the error I am getting.(as Ridham Tarpara asked )

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /</pre>
</body>
</html>
0 Answers
Related