I am trying to set up an email form using EmailJS. When the user clicks on the submit button, the details within the form will be sent my backend express server. If anyone could point me in the right direction, I would really appreciate it.
When I hit submit on my form, I get these two errors:
POST http://localhost:5000/send-email 500 (Internal Server Error)
‘AxiosError’, code: ‘ERR_BAD_RESPONSE’, config: {…}, request: XMLHttpRequest, …}
Here is my Contact.jsx
import {React, useRef} from 'react';
import "./styles/contact.css"
import axios from "axios";
const Contact = () => {
const form = useRef();
const sendEmail = (e) => {
// Prevent page refresh
e.preventDefault();
const formData = new FormData(form.current);
const templateParams = {
user_name: formData.get('user_name'),
user_email: formData.get('user_email'),
message: formData.get('message'),
};
// Send request for back-end
axios.post('http://localhost:5000/send-email', {
serviceID: import.meta.env.VITE_REACT_PORTFOLIO_SERVICE_KEY,
templateID: import.meta.env.VITE_REACT_PORTFOLIO_TEMPLATE_KEY,
templateParams: templateParams,
})
.then(response => {
if (response.data.status === "success") {
console.log('Email sent');
} else {
console.log("Failed to send email");
}
})
.catch(error => {
console.error("Error:", error);
});
// Reset the form
form.current.reset();
};
return (
<>
<h1 id = "contact" className='form-header'> Let's Chat! ☕ </h1>
<form className = "form-container" ref={form} onSubmit={sendEmail}>
<div className='input-container'>
<input type="text" name="user_name" placeholder='Ex. John Doe' required/>
</div>
<div className='input-container'>
<input id = "user-email" type="email" name="user_email" placeholder= "Ex. [email protected]" required/>
</div>
<div className='message-container'>
<textarea name="message" placeholder='Your Message...' required/>
</div>
<input className = "submit-btn" type="submit" value="Send" />
</form>
</>
);
};
export default Contact;
And here is my server.js
import express from "express"; // Backend framework
import dotenv from "dotenv";
import cors from "cors"; // Middleware
import bodyParser from "body-parser"; // Parse JSON from front-end
import emailjs from "@emailjs/browser";
// Intialize express, dotenv and assign port
const app = express();
const port = 5000;
dotenv.config();
app.use(cors());
app.use(bodyParser.json());
// import.meta.env is for client-side only
emailjs.init({
publicKey: process.env.VITE_REACT_PORTFOLIO_PUBLIC_KEY,
blockHeadless: true, // Prevent spam
});
// Listen to the port for changes
app.listen(port, () => {
console.log("Server is running on port " + port);
});
// Handle request from front-end
app.post("/send-email", (req, res) => {
const { serviceID, templateID, templateParams } = req.body;
emailjs
.send(serviceID, templateID, templateParams)
.then((response) => {
res.status(200).json({ status: "success", data: response });
})
.catch((error) => {
res.status(500).json({ status: "error", error: error });
});
});
I set up an express server to better hide my api key. I expected to be able to use axios to push my request to my backend, where my backend would send the request to EmailJS.
I’m confident that there are no issues with my .env file, as it was able to work locally when my project only had a front-end
griddy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.