简体   繁体   English

接收来自 API 调用的编码 JSON 响应

[英]Receiving encoded JSON response from API call

I'm sending a POST request to a REST API endpoint, and am receiving JSON response back filled with question mark diamonds and other unicode characters. I'm sending a POST request to a REST API endpoint, and am receiving JSON response back filled with question mark diamonds and other unicode characters. But when I test API on Postman, I am correctly receiving JSON response.但是当我在 Postman 上测试 API 时,我正确地收到了 JSON 响应。 Here is my code for calling API:这是我调用 API 的代码:

xhr.open(method,url);
xhr.setRequestHeader("Authorization", "Bearer" + " " + accessToken);
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
     console.log(xhr.status);
     console.log(xhr.responseText);
  }};
xhr.send(JSON.stringify(data));

The response I'm getting is like this: ��}�r�8���|ʧj���t���<Pe3�H���8�灖(��2�?��=S]�?䜟�_r��I�"我得到的响应是这样的:��}�r�8���|ʧj���t����<Pe3�H���8�灖(��2�?��=S] ??䜟�_r��我�”

If you are supposed to run this Javascript code on browsers, then why not just use fetch ?如果您应该在浏览器上运行此 Javascript 代码,那么为什么不直接使用fetch呢? The problem you are facing is most likely because the response sent from the server is compressed.您面临的问题很可能是因为从服务器发送的响应被压缩。 To solve this you would need to implement another library to decompress the response before using it.要解决这个问题,您需要在使用响应之前实现另一个库来解压缩响应。 Rather than overcomplicating the code by trying to decompress the response by using another library, just use fetch instead which would automatically do the job for you.与其通过尝试使用另一个库来解压缩响应来使代码过于复杂,不如使用fetch代替它会自动为您完成这项工作。 You can use fetch on browsers by default.默认情况下,您可以在浏览器上使用fetch Try this,尝试这个,

fetch(url, {
  method,
  headers: {
    'Authorization': `Bearer ${accessToken}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
  .then(response => response.json()) // parse JSON response
  .then(data => console.log(data))   // log data
  .catch(console.error);             // log errors

See, https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API见, https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM