Node.js/http:修订间差异
来自康健生活
< Node.js
创建页面,内容为“== 标题文字 == == 示例 == <syntaxhighlight lang="javascript"> const https = require('https'); function formatResData(data, headers) { const type = headers['c…” |
|||
| 第1行: | 第1行: | ||
== 标题文字 == | == 标题文字 == | ||
== | == 实现示例 == | ||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
const https = require('https'); | const https = require('https'); | ||
2022年4月21日 (四) 07:17的最新版本
标题文字
实现示例
const https = require('https');
function formatResData(data, headers) {
const type = headers['content-type'];
if (!type || type?.indexOf('application/json') !== -1) {
if (typeof data === 'string') {
try {
data = JSON.parse(data);
} catch (e) { /* Ignore */ }
}
}
return data;
}
// 封装get请求
function get(url, headers = {}) {
return new Promise((resolve, reject) => {
const req = https.get(url, { headers }, res => {
let had = false;
res.setEncoding('utf8');
res.on('data', (chunk) => {
had = true;
res.data = formatResData(chunk, res.headers);
resolve(res);
});
res.on('end', () => {
if (had) return;
resolve(res);
});
});
req.on('error', e => {
reject(e);
});
}).catch(e => {
throw new Error(e || 'Request error');
});
}
// 封装POST请求
function post(url, data, headers = {}) {
return new Promise((resolve, reject) => {
const req = https.request(url, { method: 'POST', headers }, res => {
let had = false;
res.setEncoding('utf8');
res.on('data', (chunk) => {
had = true;
res.data = formatResData(chunk, res.headers);
resolve(res);
});
res.on('end', () => {
if (had) return;
resolve(res);
});
});
req.on('error', e => {
reject(e);
});
// 写入请求的数据
data && req.write(JSON.stringify({data}));
req.end();
}).catch(e => {
throw new Error(e || 'Request error');
});
}
module.exports = {
get,
post
};
No categories