【问题标题】:Issues to have content type changed to Json (XMLHttpRequest)将内容类型更改为 Json (XMLHttpRequest) 的问题
【发布时间】:2020-02-03 17:41:49
【问题描述】:
    let data = JSON.stringify({
    "from": "testnumber",
    "to": "testnumber",
    "text": "Test SMS."
});

let XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

let xhr = new XMLHttpRequest();

xhr.withCredentials = false;

xhr.addEventListener("readystatechange", function () {
   if (this.readyState === this.DONE) {
        console.log(this.responseText);
    }
});


xhr.open("POST", "https://thaina.free.beeceptor.com", true);
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.setRequestHeader('accept', 'application/json');

xhr.send(data);

我执行的更改无关紧要,内容类型始终是文本/纯文本。您有什么建议吗?

使用此代码进行蜂鸣器测试

【问题讨论】:

  • 读取“response”(不是responseText):console.log(xhr.response),或者将文本处理为console.log(JSON.parse(xhr.responseText));
  • the content-type is always text/plain 是指服务器作为响应头发送的内容吗?如果是这种情况,那么您无法更改其他人的服务器发送给您的内容
  • 另一方面,如果您指的是请求标头,那么您的代码可以工作...在浏览器中...无论require("xmlhttprequest") 是什么,可能与浏览器 XMLHttpRequest 不完全一样...也许尝试'content-type' 而不是'Content-type' - 值得一试

标签: javascript json xmlhttprequest content-type


【解决方案1】:

node XMLHttpRequest 好像有点问题

使用xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');

然后就可以了

该模块中导致问题的代码是

  if (!headers["Content-Type"]) {
    headers["Content-Type"] = "text/plain;charset=UTF-8";
  }

在您设置的所有标题之后添加 Content-Type - 因为您设置了 Content-type 这是一个不同的标题

代码应该是

  if (!headersCase["content-type"]) {
    headers["Content-Type"] = "text/plain;charset=UTF-8";
  }

【讨论】:

  • 非常感谢您的完整解释,如果事实上您的建议非常有效!
猜你喜欢
  • 2014-09-15
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多