I am trying to send a form data to an api and i am able to get the data on the frontend butt when i am sending the request to the api am getting an error which i am not able to solve here is the code of the js where i am sending the data to the api
const value = {
name: document.getElementById("name").value,
designation: document.getElementById("designation").value,
companyName: document.getElementById("companyName").value,
email: document.getElementById("email").value,
phoneNumber: document.getElementById("phoneNumber").value,
pinCode: document.getElementById("pinCode").value,
location: document.getElementById("location").value,
message: document.getElementById("message").value,
};
const formReset = document.getElementById("contactForm");
formReset.reset();
const data = JSON.stringify(value);
console.log(data);
console.log(value.email);
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
let requestOptions = {
method: "POST",
headers: myHeaders,
body: JSON.stringify(value),
redirect: "follow",
};
fetch(
"https://us-central1-gmbexample-f23ef.cloudfunctions.net/api/forms",
requestOptions
)
.then((response) => response.text())
.then((result) => {
console.log(result);
alert(
"Your form has been submitted successfully."
);
})
.catch((error) => console.log("error", error));
and here how i am handling the backend request
const functions = require("firebase-functions");
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
require("dotenv").config();
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With",
"Content-Type",
"Accept"
);
});
app.use(bodyParser.urlencoded({ extended: true }));
// URL => /api/reports (PUT)
// .put("/reports", reportsServer);
app.post("/forms", async (req, res) => {
console.log(req.body);
res.status(200).send("oj");
});
exports.api = functions.https.onRequest(app);
error i am getting is access to fetch at 'https://us-central1-gmbexample-f23ef.cloudfunctions.net/api/forms' from origin 'https://gmbexample-f23ef.firebaseapp.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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
can anyone suggest any solution