简体   繁体   中英

HTML form submission to firebase function

I am looking to submit a simple HTML form from a frontend website (no JS framework) to a cloud function hosted with firebase

import * as functions from "firebase-functions";
import * as hcaptcha from "hcaptcha";

const secret:string = functions.config().hcaptcha.key;
export const sendEmail = functions.https.onRequest(async (request, response) => {
    console.log(secret)
    let formBody: formBody = request.body
    console.log(typeof(formBody))
    try {

        let result: VerifyResponse = await hcaptcha.verify(secret, formBody.hcaptchaResponse)
        functions.logger.info(result);
        if (result.success) {
            //send email to the magic of internet 
            functions.logger.info("Verification Success")
            response.sendStatus(200)
        }
        else {
            throw new Error('Verification Failed')
        }
    }
    catch (err) {
        functions.logger.error(err)
    }

I am getting the response.body as a string when I console log the type so am unable then to parse the formBody into hcaptcha, I have tried having the front end send application type as application/x-www-form-urlencoded too but no change

Here is the frontend code:

    <script type="text/javascript">
        function onSubmit(token) {
            const contactForm = document.querySelector('#myform')

            const params = {
                name: contactForm.elements.name.value,
                email: contactForm.elements.email.value,
                message: contactForm.elements.message.value,
                hcaptchaResponse: token
            };
            const options = {
                method: 'POST',
                body: params,
                'contentType':'application/json'
            };
            fetch('https://funURL.com/sendEmail', options)
                .then(response => console.log(response))
                .catch(err=>console.log(err))
        }

  </script>

and the form

    <form id="myform">
            <div class=" row">
                <div class="col-6 col-12-mobilep">
                    <input type="text" name="name" value="email@email.com" placeholder="Name" />
                </div>
                <div class="col-6 col-12-mobilep">
                    <input type="email" name="email" value="email@email.com" placeholder="Email@email.com" />
                </div>
                <div class="col-12">
                    <textarea name="message" placeholder="Message" value="email@email.com" rows="6"></textarea>
                </div>
                <div class="col-12">
                    <ul class="actions special">
                        <li>
                            <input class="h-captcha" data-sitekey="12345"
                                data-callback="onSubmit" type="submit" id="btnSubmit" value="Send Message"
                                data-size="invisible" />
                        </li>
                    </ul>
                </div>
            </div>
            <br />
        </form>

OK so few things I found out:

  1. is that CORS is needed to send an application/JSON content type ( https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch )

  2. I was setting the headers wrong should have been

     const options = { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(params),

    }

  3. With CORS on the cloud firebase functions a barebone implementation looks like:

     export const sendEmail = functions.https.onRequest(async (request, response) => { corsHandler(request, response, () => { try { let formBody: formBody = request.body console.log(formBody.hcaptchaResponse) } catch (err) { functions.logger.error(err) } });
  4. my body in the fetch request needed to be stringified to match the content-type

    body: JSON.stringify(params)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM