Netlify functions with axios

Viewed 565

I want to make my form submission happen server-side in order to not expose my API key. I plan to do this with netlify functions however I don't know how that would look with Axios. I've looked for examples on how to do this but I don't seem to find any. Could some help me I'm stuck as to what to put inside my the Netlify function? If anyone has worked with these two programs and could provide a hand that would be helpful here is my javascript with my submission function.

 var form = document.querySelector("#user_form");

    let reqHeaders = {
        headers: {
            Authorization: "Bearer",
        }
    }

    let url = ""

    let reqData = {
        records: [
            {
                fields: null
            }
        ]
    }

    let formData = {
        firstName: "",
        lastName: "",
        email: ""
    }

    function logData(id, dataObj, value) {

        dataObj[id] = value;

        console.log(value)
    }

    function formMessg (id) {
        document.querySelector(id).style.display = "block";

        setTimeout(function(){
            document.querySelector(id).style.display = "none";
            form.reset();
        }, 2500)
    }

    form.addEventListener("submit", function (e) {
        e.preventDefault();

        let spam = document.getElementById('spam').value;

       

        try {
            for(const data in formData){
                if(formData[data] === "" || spam.length !== 0){
                    const error = new Error();
                    error.notVaild = true;
                    throw error;
                }
            }

        reqData.records[0].fields = formData;

        console.log(reqData);

        axios.post(url, reqData, reqHeaders).then((res) => {
            formMessg ('.success-messg');
            form.style.display = "none";
            })
        .catch ((err) => {
            throw err;
            });
        } catch (err){
            if (err.reponse){
                formMessg ('.fail-messg');
            } else if (err.request) {
                formMessg ('.fail-messg');
            } else if ("Notvalid") {
                formMessg ('.fill-messg');
            }else {
                console.log(err);
            }
        }
    });

0 Answers
Related