node.js https.get()解决标题和正文之间的混淆
我最近开始学习node.js 在node.js https模块中,我使用node.js https.get()解决标题和正文之间的混淆,node.js,https,Node.js,Https,我最近开始学习node.js 在node.js https模块中,我使用https.get()发出服务器请求和iconsole.dir(res.header)这会给我响应头,但当我尝试console.dir(res.body)时,这会给我未定义的 我在互联网上做了一些调查,我发现我需要调用数据事件来记录尸体。这让我很困惑,为什么我不能直接记录body,而header的数据格式是string,body的数据格式是buffer?下面是一些使用https.request方法(与get相同)的示例,它们
https.get()发出服务器请求
和iconsole.dir(res.header)
这会给我响应头,但当我尝试console.dir(res.body)
时,这会给我未定义的
我在互联网上做了一些调查,我发现我需要调用数据事件来记录尸体。这让我很困惑,为什么我不能直接记录body,而header的数据格式是string,body的数据格式是buffer?下面是一些使用https.request方法(与get相同)的示例,它们应该向您展示一些使用该方法的方法。这些示例使用了httpbin.org站点,这是一个非常有用的站点,用于处理此类代码
const https = require ('https');
// Example 1
// This will return the IP address of the client
var request = https.request({ hostname: "httpbin.org", path: "/ip" }, (res) => {
console.log('/ip', res.statusCode);
res.on('data', (d) => {
console.log('/ip response: ', d.toString());
});
});
request.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
request.end();
// Example 2
// This will return some simple data about the get request
request = https.request({ hostname: "httpbin.org", path: "/get"}, (res) => {
console.log('/get', res.statusCode);
res.on('data', (d) => {
console.log('/get response: ', d.toString());
});
});
request.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
request.end();
// Example 3
var data = JSON.stringify({firstName: 'Mike', secondName: 'Jones'});
// This will return the data passed request
request = https.request({ hostname: "httpbin.org", path: "/anything", method: "GET", headers:
{ 'Content-Length': data.length, 'Content-Type': 'application/json' }}, (res) => {
console.log('/anything', res.statusCode);
res.on('data', (d) => {
console.log('/anything response: ', d.toString());
});
});
request.write(data);
request.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
request.end();
您正在尝试记录get请求的响应吗?在这种情况下,您需要在successresponse方法中添加一个console.log。