2

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]

hearty
  • 691
  • 5
  • 10
  • 15

2 Answers2

10

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());
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • everything seems fine but in the data that I m getting back two array values are null shopProductsCount and shopProducts....but the other values seems to be right I mean like responseResult etc – hearty Jun 04 '18 at 09:57
  • @hearty - Fairly certain that will be an unrelated issue. – T.J. Crowder Jun 04 '18 at 10:05
-2

Read this answer

You have to insert at least formBody = formBody.join("&"); after the loop.

Aliaksei Zhukau
  • 217
  • 4
  • 12
  • 1
    If the answer to that question answers this question (and I think you're right, it does), vote to close as duplicate, don't post a link to the answer in an answer. – T.J. Crowder Jun 04 '18 at 09:22