Search code examples
javascriptjsonpostmanstrapi

Values not being sent in POST request to API (Postman + Strapi)


Im trying to POST an entry to Strapi through Postman. I have three fields in my endpoint, which are boxname + boxlocation + boxnumber. Two first are string and the last is integer. But for some reason my values doesnt get posted, they all turn up as null.

Any idea why? I ended up using Postman to try, because my Javascript wouldn't work either:

async function pushToStrapi(token, boxname, boxlocation, ownerid) {
  var xhr = new XMLHttpRequest();
  var url = "http://localhost:1337/boxes";
  xhr.open("POST", url, true);
  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
          var json = JSON.parse(xhr.responseText);
      }
  };
  var data = JSON.stringify({"boxname": ""+boxname+"", "boxlocation": ""+boxlocation+"" }});
  xhr.send(data);
}

As you can see, Im trying to POST an entry through the API endpoint of Strapi through Postman.


Solution

  • Theres a syntax error. Change:

    var data = JSON.stringify({"boxname": ""+boxname+"", "boxlocation": ""+boxlocation+"" }});
    

    To:

    var data = JSON.stringify({"boxname": ""+boxname+"", "boxlocation": ""+boxlocation+"" });
    

    If you prefer to use shorthand, you can do something like this:

    var data = JSON.stringify({boxname, boxlocation});