我无法以可读格式获取HTTP GET请求对Dynamics CRM的响应中的数据。它始终以unicode字符返回(即正文:'\u001f�\ b \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0004 \u0000�\ m�۸ \u0011�+Ķ= \��Z���\ u0004A7 /�\ u000b ...'
当我在Postman中发送相同的GET请求时,我收到的响应的主体将以可读的方式进行格式化,并返回我需要的所有KnowledgeArticles-因此(据我所知),http请求很好(只要因为授权令牌保持最新状态)。
我只是完全停留在如何将响应正文中的unicode数据解析为可读的文本中,以便在代码逻辑中使用该文本以将正确的结果返回给用户。
下面是我用于解析调用get请求和解析响应的代码
const restify = require('restify');
const errors = require('restify-errors');
const port = process.env.PORT || 3000;
const request = require("request");
const stringify = require('stringify');
const server = restify.createServer({
name: 'restify headstart'
});
server.listen(port, () => {
console.log(`API is running on port ${port}`);
});
ar options = { method: 'GET',
url: 'https://########.crm.dynamics.com/api/data/v9.1/knowledgearticles',
qs: { '$select': 'content,title' },
headers:
{ 'cache-control': 'no-cache',
Connection: 'keep-alive',
'accept-encoding': 'gzip, deflate',
cookie: '###################',
Host: '#####.crm.dynamics.com',
'Postman-Token': '#######',
'Cache-Control': 'no-cache',
'User-Agent': 'PostmanRuntime/7.13.0',
Authorization: 'Bearer ################# buncha crap #####',
Accept: 'application/json'
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
// below are all of my attempts at parsing 'response'
* let aaa = response;
* let aaa = response.toJSON();
* let aaa = JSON.stringify(response);
* let aaa = response.toString();
* let aaa = response.toJSON(body);
* let aaa = response.setEncoding('binary');
* let aaa = aaaa.toJSON();
// none of the above result in my response logging into readable text
console.log(aaa);
});
最佳答案
您已压缩response
,删除了'accept-encoding': 'gzip, deflate'
标头
const options = {
method: "GET",
url: "https://contactcenter.crm.dynamics.com/api/data/v9.1/knowledgearticles",
qs: {"$select": "content,title"},
headers: {
"cache-control": "no-cache",
"connection": "keep-alive",
"cookie": "...",
"host": "contactcenter.crm.dynamics.com",
"postman-token": "...",
"User-Agent": "PostmanRuntime/7.13.0",
"authorization": "Bearer ...",
"accept": "application/json"
}
}
或添加
gzip: true
来请求选项const options = {
method: "GET",
url: "https://contactcenter.crm.dynamics.com/api/data/v9.1/knowledgearticles",
qs: {"$select": "content,title"},
headers: {
"cache-control": "no-cache",
"connection": "keep-alive",
"accept-encoding": "gzip, deflate",
"cookie": "...",
"host": "contactcenter.crm.dynamics.com",
"postman-token": "...",
"User-Agent": "PostmanRuntime/7.13.0",
"authorization": "Bearer ...",
"accept": "application/json"
},
gzip: true
};
或手动解压缩您的
response