javascript - 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 中测试了确切的requestBody
JSON,选择application/json
了它content-type
并将其添加url
到端点并且它起作用了。使用 Postman,我能够连接到 REST API(在那里我看到我的 JSON 对象正在接收),然后我得到了所需的响应。
我不明白为什么邮递员工作正常,但XMLHttpRequest
没有。Postman 在发送 JSON 对象时是否使用了某种额外的处理?我错过了什么XMLHttpRequest
吗?
任何尝试的想法将不胜感激!
解决方案
如果请求方法是 GET 或 HEAD,则忽略 body 参数并将请求正文设置为 null。
推荐阅读
- java - 当我正在读取的文件存在时,Java 程序给了我 FileNotFoundException,但如果我处理异常,则工作得很好
- java - 将 Oracle Java 存储过程连接到 MySQL
- keycloak - 从 Nodejs 访问 Keycloak 组属性
- spring - Spring Security 5 oauth2 登录
- reactjs - Chrome 加载 React 应用程序中的“WebExtension::executeScript:内容脚本注入 VM149:1”
- python - 在函数启动时初始化新类时出错
- scroll - 如何使用触摸板在 Windows 上的 Netbeans 8.2 中启用水平滚动?
- php - 使用 PHP SDK 向 Twilio Studio 发送可选参数以触发 Flow
- excel - ActiveWorkbook.Names.Add 生成错误“此名称的语法不正确”。
- java - Pivotal 服务器实例抛出错误“无法启动组件”,但对于不同目录中的同一实例工作正常