-2

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

Amar
  • 1
  • 1
  • The solution is in the error. The server must provide an 'Access-Control-Allow-Origin' header. period. that's it. – gforce301 Sep 07 '20 at 18:37
  • @gforce301 I am adding in the backend – Amar Sep 07 '20 at 18:40
  • `res.header` accepts either 2 strings `field, value` or a JSON object containing headers as `key-value` pairs. Please fix the second call to `res.header` and check – Kunal Kukreja Sep 07 '20 at 18:41
  • @KunalKukreja is it possible to apply a cors rule for a particular request like in my case i want to apply cors for /forms only and i am trying your suggested solution – Amar Sep 07 '20 at 18:45
  • @Amar You might want to use this: https://www.npmjs.com/package/cors#enable-cors-for-a-single-route. This will save you all the hassle – Kunal Kukreja Sep 07 '20 at 18:58
  • @KunalKukreja i have added the allow origin to * yet i am getting the error and second part i have removed can you suggest me a proper solution – Amar Sep 07 '20 at 19:04

2 Answers2

-1

CORS is a security protocol used to ensure that a client making an API request to your API is authorized. The browser performs a "preflight" check to determine this by sending an HTTP OPTIONS request to your API, which tells the client if it has that authority.

Your API will nee to respond to OPTIONS requests with the required CORS headers: https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request.

At minimum, your response to the OPTIONS request should contain the following headers:

Access-Control-Allow-Origin: https://foo.bar.org

Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE

You can substitute values here for *, but if you are planning on not making your API public, then using specific domains is preferred for security so that CORS is actually doing something useful.

Chewy
  • 196
  • 1
  • 12
-1

Have you tried to use chrome tool https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf ?

  • That won't work for a request that triggers a preflight (as in this case) and isn't practical in a production environment anyway (asking people to install a browser extension to disable a security feature is unreasonable). – Quentin Sep 07 '20 at 18:39