Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post a x-www-form-urlencoded data properly using javascript? [duplicate]

Tags:

javascript

I have written a JS function to post categoryId and shopId and page:0 to an api and this is my funciton :-

 getInsideMenu(categoryid,shopid){
        var formBody = [];
        var details={
             'categoryId':categoryid,
             'shopId':shopid ,
             'page':'0'
        };
        for (var property in details) {
              var encodedKey = encodeURIComponent(property);
              var encodedValue = encodeURIComponent(details[property]);
              formBody.push(encodedKey + "=" + encodedValue);
        }
                return fetch(
            `${serverAddress}/api/shopProducts`,
            {
                method: 'POST',
                body: formBody,
                headers: {
                   'Content-Type': 'application/x-www-form-urlencoded'
                }
            }
        ).then((res)=>(res.json()))
    },

But I'm getting null .I suppose the function is not defined properly. What can be done to fix it. It works well in POSTMAN. [![this is in postman how I send][1]][1]

like image 520
hearty Avatar asked Jan 27 '26 20:01

hearty


1 Answers

You're building an array of encoded name/value pairs and passing that directly as the body of the POST. But fetch doesn't accept an array in that parameter.

The minimal change to your code would be to join the array using & as the separator:

return fetch(
    `${serverAddress}/api/shopProducts`,
    {
        method: 'POST',
        body: formBody.join("&"), // <===== here
        headers: {
           'Content-Type': 'application/x-www-form-urlencoded'
        }
    }
). /* etc */

Alternately, use FormData, as this is exactly what it's for: :-)

getInsideMenu(categoryid,shopid){
    var formBody = new FormData();
    formBody.set("categoryId", categoryid);
    formBody.set("shopId", shopid);
    formBody.set("page", "0");
    return fetch(
        `${serverAddress}/api/shopProducts`,
        {
            method: 'POST',
            body: formBody,
            headers: {
               'Content-Type': 'application/x-www-form-urlencoded'
            }
        }
    ).then((res)=>(res.json()));
}

(Depending on your needs, you might use set or append. The above uses set.)


Side note 1:

This line:

).then((res)=>(res.json()));

...doesn't need most of those ():

).then(res => res.json());

Side note 2:

Don't forget to check for success; failing to do so is a common pitfall when using fetch. fetch doesn't reject on HTTP error (like 404 or 500). If you want to reject on HTTP error, you have to do it yourself:

return fetch(/*...*/)
    .then(res => {
        if (!res.ok) {
            throw new Error(res.status);
        }
        return res;
    })
    .then(res => res.json());
like image 175
T.J. Crowder Avatar answered Jan 30 '26 11:01

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!