Axios decompile object's parameters dynamically for post request

Viewed 20

I am in the process of locating all my requests (in my react project) in a single location so that repeated code is reduced, better & easier future updates.

Here is the old post request I was using from the calling component:

 const post_request = await Axios.post(`${window.ipAddress.ip}/ContactForms/add`,
                    JSON.stringify({
                        name: contactUs.name, email: contactUs.email, message: contactUs.message, generatedDate: todayDate
                    }), { withCredentials: false, headers: { 'Content-Type': 'application/json' } });

This request is verified to work.

Now in the same calling component I want to instead run this:

    const postRequest = async () => {
        if (contactUs.name !== "" && contactUs.email !== "" && contactUs.message !== "") {
            var todayDate = new Date().toISOString().slice(0, 10);
            basePostRequestWithoutCredentails(
                "ContactForms/add", 
                {name: contactUs.name, email: contactUs.email, message: contactUs.message, generatedDate: todayDate}
            )
        }
    }

Which forwards request to this function:

export const basePostRequestWithoutCredentails = async (endpoint, object) => { // finish this request
    var result = ""
    var errorMsg = {};
        try {
            const post_request = await Axios.post(`${window.ipAddress.ip}/${endpoint}`,

              JSON.stringify({object: object}), // <<<<<<<<< THIS IS ISSUE

            { withCredentials: false, headers: { 'Content-Type': 'application/json' } });

            if (post_request.status == 201) {
                result = post_request.data;
            }
            else {
                // handle error here
            }
        }
        catch (err) {
            if (!err?.response) { errorMsg = 'No Server Response' }
            else { errorMsg = 'Other error' }
            console.log("error")
        }
    return (result);
}

The issue lies within the marked line. My server does not recognize this object because of the formatting difference from the original request, I would like to use this function for various post requests containing different object.

How do I pass each individual parameterName: parameterData from object into Axios body?

0 Answers
Related