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

hearty

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]

T.J. Crowder

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());

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to send post request with x-www-form-urlencoded body

How to get and parse JSON response from x-www-form-urlencoded POST, RestTemplate (Java)?

How to force Angular2 to POST using x-www-form-urlencoded

CORS issue when trying to do JQuery post with json data, but not with plain text or x-www-form-urlencoded

application/x-www-form-urlencoded or multipart/form-data?

Send sensitive data using POST+application/x-www-form-urlencoded

how to send x-www-form-urlencoded data using ngResource module with angular?

how to post data in node.js with content type ='application/x-www-form-urlencoded'

How do I post data using okhttp library with content type x-www-form-urlencoded?

How to POST with application/x-www-form-urlencoded header and URLSearchParams using isomorphic-fetch

How to post (x-www-form-urlencoded) Json Data using Retrofit?

Convert encoded application/x-www-form-urlencoded post data to json object

How to send bearer token and x-www-form-urlencoded data using Node Request

How to POST content as application/x-www-form-urlencoded

Post controller recognizes only parameters sent by "from-data" or "x-www-form-urlencoded" from postman

How to POST x-www-form-urlencoded in retrofit

How to post request with spring boot web-client for Form data for content type application/x-www-form-urlencoded

POST using cURL and x-www-form-urlencoded in PHP returning Access Denied

How to escape + in post call content type as application/x-www-form-urlencoded

How to send post request with x-www-form-urlencoded body with loopj-async-http library

How to convert x-www-form-urlencoded post Message to JSON post Message?

How to send x-www-form-urlencoded in a post request in webclient?

POST application/x-www-form-urlencoded Body to REST API using Jitterbit

how to post body x-www-form-urlencoded using webclient?

How to do a post request using FORM-DATA or x-www-form-urlencoded with Android?

Server-side Blazor Post using HttpClient with x-www-form-urlencoded

Trying to make an API POST using application/x-www-form-urlencoded in a wpf desktop app

How to post an array of values using `UrlFetchApp.fetch` with `application/x-www-form-urlencoded`?

How to do a x-www-form-urlencoded POST login using cypress?