1
0
Code Issues Pull Requests Projects Releases Wiki Activity GitHub Gitee
tools/utils/requestUtils.js

66 lines
1.6 KiB
JavaScript
Raw Permalink Normal View History

2022-09-30 00:51:08 +08:00
const request = require('request');
async function get(url) {
return await query({
method: 'GET',
url: url,
json: true,
});
}
async function getApiResult(url, params = null) {
return await query({
method: 'GET',
url: url,
2022-10-09 17:37:57 +08:00
...params || {}
2022-09-30 00:51:08 +08:00
});
}
async function query(opts) {
var return_data = await new Promise((resolve, reject) => {
// console.log("opts", opts);
request(opts, (error, response, result) => {
// console.log("error, result", error, result);
if (!error && (response.statusCode == 200)) {
// 请求成功
resolve(result);
} else {
// 请求失败
console.error(`error is ${error}`);
reject(error);
}
});
});
// console.log(`return_data is ${JSON.stringify(return_data)}`);
return return_data;
}
2022-10-28 00:23:50 +08:00
async function getRedirectUrl(url) {
return await new Promise((resolve, reject) => {
request({
url: url,
followRedirect: false
}, function (err, res, body) {
if (err) {
reject(err);
}
// console.log(res.headers.location);
2022-11-10 15:50:41 +08:00
// 兼容 node 12
// resolve(res?.headers?.location);
if (res && res.headers) {
resolve(res.headers.location);
} else {
resolve(undefined);
}
2022-10-28 00:23:50 +08:00
});
});
}
2022-09-30 00:51:08 +08:00
module.exports = {
get: get,
getApiResult: getApiResult,
query: query,
2022-10-28 00:23:50 +08:00
getRedirectUrl: getRedirectUrl,
2022-09-30 00:51:08 +08:00
}