查看“︁Node.js/http”︁的源代码
来自康健生活
←
Node.js/http
因为以下原因,您没有权限编辑该页面:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
== 标题文字 == == 实现示例 == <syntaxhighlight lang="javascript"> 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 }; </syntaxhighlight>
返回
Node.js/http
。
导航菜单
康健生活
搜索
user-page
通知
user-interface-preferences
个人工具
登录
五一
多读书,多运动,多到远处走走,再看看不一样的世界。