【问题标题】:REST API receives 'null' from XMLHttpRequest - same request with Postman works?REST API 从 XMLHttpRequest 接收“null”-与 Postman 相同的请求有效吗?
【发布时间】:2023-03-23 12:16:01
【问题描述】:

我有一个非常基本的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 中测试了确切的 requestBody JSON,选择 application/json 作为 content-type 并将 url 添加到端点并且它工作。使用 Postman,我能够连接到 REST API(在那里我看到我的 JSON 对象正在接收),然后我得到了所需的响应。

我不明白为什么 Postman 可以正常工作,但 XMLHttpRequest 不能。 Postman 在发送 JSON 对象时是否使用了某种额外的处理?我在XMLHttpRequest 中遗漏了什么吗?

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

【问题讨论】:

    标签: javascript json rest xmlhttprequest


    【解决方案1】:

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

    【讨论】:

    • 您可以将正文序列化为 GET 参数格式,然后将其添加到 URL 的末尾。或者您可以尝试将其更改为 POST。
    猜你喜欢
    • 2018-07-27
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多