I am getting a CORS error when trying to submit a form from my website to my Express server. Here is the setup and the problem:
Server (Express) Code:
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors({
origin: 'https://www.teckwithfeya.com'
}));
app.use(express.json());
app.post("/send", (req, res) => {
console.log(req.body); // Log the received data
res.send("Form submitted successfully");
});
app.listen(7000, () => {
console.log("Server is running on port 7000");
});
Client-side JavaScript:
document.addEventListener("DOMContentLoaded", function () {
const contactForm = document.getElementById("contactForm");
contactForm.addEventListener("submit", function (event) {
event.preventDefault();
const formData = new FormData(contactForm);
fetch("https://www.teckwithfeya.com/send", {
method: "POST",
body: formData
})
.then(response => response.text())
.then(data => {
console.log(data);
})
.catch(error => {
console.error("Error:", error);
});
});
});
When I submit the form, I get the following CORS error in the browser console:
Access to fetch at ‘https://www.teckwithfeya.com/send’ from origin ‘https://www.teckwithfeya.com’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
I have set up CORS on my Express server with cors middleware.
I tried using both fetch with JSON and FormData.