Javascript Capture Form Values and Send via Api

19 views Asked by At

I have a subscription form on my website. I'am capturing the email address form form and trying to send them via api. When I run the I'm getting the error below:

"Access to fetch at 'https://domainname.com/api/subscribers' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request."

Here is my code:

<form id="subscriptionForm">
    <input type="email" id="emailInput" placeholder="Email Address" required>
    <button type="submit">Subscribe</button>
</form>

<script>
    document.getElementById("subscriptionForm").addEventListener("submit", function (event) {
        event.preventDefault();

        var email = document.getElementById("emailInput").value;
        var data = { email: email };
        var apiKey = "12345678";

        fetch("https://domainname.com/api/subscribers", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-DemoAPI-Key": apiKey
            },
            body: JSON.stringify(data)
        })
        .then(function (response) {
            if (response.ok) {
                console.log("Success");
            } else {
                console.error("Error");
            }
        })
        .catch(function (error) {
            console.error("Error:", error);
        });
    });
</script>

Do you have any idea about what I'm doing wrong?

I'am capturing the email address form a form on my website and trying to send them via api. When I run the I'm getting error.

1

There are 1 answers

0
Stefan Avramovic On

CORS error occurs when the server doesn't return the CORS headers required. For example, https://domain-a.com tries to make an API request to https://domain-b.com that doesn't allow it to access its resources. You most probably need to use backend to get access or modify api to send CORS headers. But if you are using authentication, don't fetch using front end.. Its a scuriti risk...