nodejs 使用https请求设置自定义参数
在使用https模块发送请求时,可以使用options参数来设置自定义参数。
例如,可以设置请求头信息、请求超时时间、代理等。
示例代码如下:
const https = require('https');
const options = {
hostname: 'www.example.com',
port: 443,
path: '/api/data',
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token'
},
timeout: 5000, // 5秒超时
proxy: 'http://localhost:8080' // 使用代理
};
const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (error) => {
console.error(error);
});
req.end();
在上面的示例中,我们设置了请求头信息和请求超时时间,并使用代理发送请求。当然,还可以根据具体需求设置其他自定义参数。
原文地址: https://www.cveoy.top/t/topic/bIrN 著作权归作者所有。请勿转载和采集!