首页 > 解决方案 > REST API 从 XMLHttpRequest 接收“null”-与 Postman 相同的请求有效吗?

问题描述

我有一个非常基本XMLHttpRequest的看起来像这样:

var requestBody = JSON.stringify(
{
   "parameter_1": ["940mbodmgpg04", "curnv_dsiofpe"],
   "parameter_2": {
        "sub_par": {
            "sub_par-entry":"en_489vb", 
            "sub_par-second-entry":"avop30kdm", 
            "toggler": ["ovofpvm235", "23rfdkvo_SDgop"]
            }
        }
}
);

var req = new XMLHttpRequest();
req.open("GET", "http://localhost:4000/api/fontstabilizer/vorq3", true);
req.setRequestHeader("Content-Type", "application/json");
req.onreadystatechange = function() {
    // do some stuff
};

req.send(requestBody);

但是,当我将它发送到 REST API 时,它会null作为正文接收。我在 Postman 中测试了确切的requestBodyJSON,选择application/json了它content-type并将其添加url到端点并且它起作用了。使用 Postman,我能够连接到 REST API(在那里我看到我的 JSON 对象正在接收),然后我得到了所需的响应。

我不明白为什么邮递员工作正常,但XMLHttpRequest没有。Postman 在发送 JSON 对象时是否使用了某种额外的处理?我错过了什么XMLHttpRequest吗?

任何尝试的想法将不胜感激!

标签: javascriptjsonrestxmlhttprequest

解决方案


如果请求方法是 GET 或 HEAD,则忽略 body 参数并将请求正文设置为 null。


推荐阅读