node.js + request =>响应显示垃圾响应

时间:2019-12-03 11:37:46

标签: node.js http request

我正在使用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);

  }
});

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

enter image description here 我需要jSON格式的结果,此请求有什么问题?

2 个答案:

答案 0 :(得分: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);

  }
});

答案 1 :(得分: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);

  }
});