值未在POST请求中发送给API(邮递员+ Strapi)

时间:2020-06-08 12:36:08

标签: javascript json postman strapi

我正在尝试通过邮递员将条目发布到Strapi。我的端点中有三个字段,分别是boxname + boxlocation + boxnumber。前两个是字符串,最后一个是整数。但是由于某些原因,我的值没有发布,它们全都显示为null。

知道为什么吗?我最终使用Postman尝试,因为我的Javascript也不起作用:

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.

3 个答案:

答案 0 :(得分:2)

存在语法错误。更改:

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

收件人:

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

如果您喜欢使用速记,则可以执行以下操作:

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

答案 1 :(得分:1)

您不能执行这种请求。

您将必须单击“正文”,然后选择“原始”格式,然后在格式下拉列表中选择“ JSON”。

然后使用您的键值编写JSON对象。

您不能在查询参数中发送参数。

答案 2 :(得分:0)

我也遇到了这个问题,我正在学习Strapi,在我的情况下,我正在JSON对象中发送ID,该ID由Strapi管理,然后我删除了ID(自动增量值)并仅发送数据。在您的示例中,我看到您没有发送ID字段,但是这一点也许可以帮助您或其他阅读者。

这是我的要求:

{
"post_name": "raw postman post",
"post_description":"raw postman post",
"post_content": "raw postman post",
"post_category": 1 }

这是有效的响应:

{
"id": 9,
"post_name": "raw postman post",
"post_description": "raw postman post",
"post_content": "raw postman post",
"post_category": {
    "id": 1,
    "category_name": "Climate",
    "category_desc": "Climate",
    "published_at": "2020-10-16T11:37:11.931Z",
    "created_at": "2020-10-16T11:35:01.418Z",
    "updated_at": "2020-10-16T11:37:11.950Z"
},
"published_at": "2020-10-22T11:35:59.714Z",
"created_at": "2020-10-22T11:35:59.722Z",
"updated_at": "2020-10-22T11:35:59.731Z"}