Every time I start my application locally I need to run:
- npm start (to start my React app)
- node server.js (to start my node.js server)
How can I host this website?
Another issue I run into:
- I run my React app on localhost:3000
- My node.js server listens on localhost:3000
As a result: When I refresh my application sometimes it says "Cannot GET /" because it is trying to GET the node.js server instead of the React App.
Here is my server.js file for reference
const express = require('express');
const nodemailer = require('nodemailer');
require('dotenv').config()
const app = express();
var bodyParser = require('body-parser')
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({
extended: true
}));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}...`);
});
const transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 587,
auth: {
user: process.env.EMAIL,
pass: process.env.PASS,
},
});
transporter.verify(function(error, success) {
if (error) {
console.log(error);
} else {
console.log("Server is ready to take our messages");
}
});
app.post('/send', (req, res, next) => {
console.log(req.body)
var name = req.body.contactName
var email = req.body.contactEmail
var subject = req.body.contactSubject
var message = req.body.contactMessage
var mail = {
from: name,
to: email,
subject: subject,
text: message
}
transporter.sendMail(mail, (err, data) => {
if (err) {
res.json({
status: 'fail'
})
} else {
res.json({
status: 'success'
})
}
})
});
Any suggestions on the correct way to do this would be appreciated. Thanks!
UPDATE
Apparently the 'Cannot Get /' is a common issue for node.js react applications and I need to add in something like this into my server.js:
app.route("/").get(function (req, res) {
res.redirect("/public/index.html");
});
Can anyone help with this method to redirect get requests to my node.js server to the home page of my react app?