I’ve made a contact form for my react app that works on localhost but once I deploy it doesn’t work anymore. Been trying different url for post, with or without port but each time it throws an error.
As it is now I get this in the console:
Error: Request failed with status code 404 at e.exports (createError.js:16)
at e.exports (settle.js:17)
at XMLHttpRequest.x (xhr.js:66)
This is how I submit the mail:
axios({
method: 'POST',
url: 'https://url.com/contact',
data: formData
}).then((response) => {
if (response.data.status === 'success') {
toast.success(
<div>
Success
</div>
);
resetForm();
} else if (response.data.status === 'fail') {
toast.error(
<div>
Error
</div>
);
}
});
This is my server:
var express = require('express');
var cors = require('cors');
var router = express.Router();
var nodemailer = require('nodemailer');
app.use(express.static('build'));
app.get('*', (req, res) => {
req.sendFile(path.resolve(__dirname, 'build', 'index.html'));
});
var transport = {
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'my_password'
}
};
var transporter = nodemailer.createTransport(transport);
transporter.verify((error, success) => {
if (error) {
console.log(error);
} else {
console.log('Server is ready to take messages');
}
});
router.post('/contact', (req, res, next) => {
var firstName = req.body.firstName;
var lastName = req.body.lastName;
var email = req.body.email;
var phoneNumber = req.body.phoneNumber;
var subject = req.body.subject;
var message = req.body.message;
var dataConsent = req.body.dataConsent;
var content = `Name:n${
firstName + ' ' + lastName
}nnnEmail:n${email}nnnPhone Number:n${phoneNumber}nnnSubject:n${subject}nnnMessage:n${message}nnnConsent:n${dataConsent}`;
var mail = {
from: email,
to: '[email protected]',
subject: subject,
text: content
};
transporter.sendMail(mail, (err, data) => {
if (err) {
res.json({
status: 'fail'
});
} else {
res.json({
status: 'success'
});
}
});
});
const app = express();
app.use(cors());
app.use(express.json());
app.use('/', router);
app.listen(3002);
And in package.json I run this script on start:
"start": "node src/server.js",