我对Node.js经验不足,但是http / https文档似乎很糟糕,而且我不知道如何获取常见的响应标头:
下面给出我的代码,如何确定statusCode和响应标头?
const promiseResponse = new Promise((resolve, reject) => {
const fullResponse = {
status: '',
body: '',
headers: ''
};
const request = https.request({
hostname: testHostname,
path: testPath,
method: testMethod,
headers: {
'x-jwt': jwt,
'content-type': contentType,
}
});
request.on('error', reject);
request.on('response', response => {
response.setEncoding('utf8');
response.on('data', chunk => { fullResponse.body += chunk; });
response.on('end', () => {
fullResponse.body = JSON.parse(fullResponse.body);
resolve(fullResponse);
});
});
request.write(JSON.stringify(testBody));
request.end();
});
promiseResponse.then(
response => {
console.log('success:', response);
},
error => {
console.error('error:', error);
}
);
答案 0 :(得分:2)
在您的代码中:
request.on('response', response => { ... });
您将获得一个响应对象。该对象是http.IncomingMessage
的实例,可以像这样访问response.statusCode
和response.headers
:
request.on('response', response => {
console.log(response.statusCode);
console.log(response.headers);
response.on('data', chunk => { fullResponse.body += chunk; });
});
许多人(包括我自己)发现更高级别的request
或request-promise
模块非常容易使用。它们建立在http.request
和https.request
的基础上,但是为您提供了更易于使用的界面。
答案 1 :(得分:0)
我正在寻找相同的东西。使用此处和其他来源的一些示例,我可以共享一个有效的node.js示例。
index.js:
// dependencies
const express = require('express');
const https = require('https');
var Promise = require('es6-promise').Promise;
const { stringify } = require('querystring');
const app = express();
// from top level path e.g. localhost:3000, this response will be sent
app.get('/', (request, response) => {
getHeaderAndDataResponse(function (res) {
console.log('getHeaderAndDataResponse returned');
response.send(res);
});
});
/**
* get all headers and data.
* date is returned to the caller
* headers ar output to console for this example.
* @param {*} callback
*/
function getHeaderAndDataResponse(callback) {
console.log('Entering getHeaderAndDataResponse');
// surround the https call with a Promise so that
// the https ansyc call completes before returning.
// Note: may need to change date to today.
let retVal = new Promise(function (success, fail) {
https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&start_date=2020-07-22',
function (resp) {
let data = '';
console.log("Got response: " + resp.statusCode);
// quick dirty way to format the headers
// output to console, but could easily be added
// to the JSON returned below.
for (var item in resp.headers) {
let h = '"' + item + '": ' + '"' + resp.headers[item] + '"';
console.log(h);
}
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
let exp = JSON.parse(JSON.stringify(data));
console.log('got data');
success(exp);
});
}).on('error', (err) => {
console.log("Error: " + err.message);
fail(err.message);
})
}).then(retVal => {
console.log('got then');
return callback(retVal);
});
}
// set the server to listen on port 3000
app.listen(3000, () => console.log('Listening on port 3000'));