66 lines
1.6 KiB
JavaScript
66 lines
1.6 KiB
JavaScript
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,
|
|
...params || {}
|
|
});
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
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);
|
|
|
|
// 兼容 node 12
|
|
// resolve(res?.headers?.location);
|
|
if (res && res.headers) {
|
|
resolve(res.headers.location);
|
|
} else {
|
|
resolve(undefined);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
module.exports = {
|
|
get: get,
|
|
getApiResult: getApiResult,
|
|
query: query,
|
|
getRedirectUrl: getRedirectUrl,
|
|
}
|