0

我正在使用 node.js + 请求将 HTTP 请求发送到 URL。我需要 JSON 响应,但我得到了垃圾字符。

这是我的 node.js 代码

var request = require('request');
var post_data = { UserName: "xxxxx", Password: "xxxxx" };

var post_options = {
  url: 'http://xxxxxxx.info/api/CoreUser/cognitoLogin',
  method: 'POST',
  form: post_data,
  headers: {
    'AppID': 'zNiphaJww8e4qYEwJ96g555HTAAbAXdj',
    'OAuth': 'xxxxxxxxxxxxxxxxxx',
    //'User-Agent': 'Super Agent/0.0.1',
    'Content-Type': 'application/json;charset=UTF-8',
  }
};
// Set up the request
request(post_options, function (error, response, body) {
  console.log(response.statusCode);
  if (!error && response.statusCode == 200) {
    console.log("200");
    console.log(response);

  }
});

但我收到了垃圾字符的回复。

在此处输入图像描述 我需要 JSON 格式的结果,这个请求有什么问题?

4

2 回答 2

0

我发现了问题,原因是 API 响应以 gZip 格式发送。这是我们必须在这里做出的改变。只需启用gzip: true它即可解决问题。

var request = require('request');
var post_data = { UserName: "xxxxx", Password: "xxxxx" };

var post_options = {
  url: 'http://xxxxxxx.info/api/CoreUser/cognitoLogin',
  method: 'POST',
  gzip: true,
  form: post_data,
  headers: {
    'AppID': 'zNiphaJww8e4qYEwJ96g555HTAAbAXdj',
    'OAuth': 'xxxxxxxxxxxxxxxxxx',
    //'User-Agent': 'Super Agent/0.0.1',
    'Content-Type': 'application/json;charset=UTF-8',
  }
};
// Set up the request
request(post_options, function (error, response, body) {
  console.log(response.statusCode);
  if (!error && response.statusCode == 200) {
    console.log("200");
    console.log(response);

  }
});
于 2019-12-04T06:28:44.477 回答
0

{ json: true }在请求呼叫中失踪

request(post_options, { json: true }, function (error, response, body) {
  console.log(response.statusCode);
  if (!error && response.statusCode == 200) {
    console.log("200");
    console.log(response);

  }
});
于 2019-12-03T11:48:50.863 回答