Last active
April 4, 2022 04:10
-
-
Save joekiller/768050ba412f7550336c43a47c838c6b to your computer and use it in GitHub Desktop.
Nodejs Typescript Https get and post
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import https from "https"; | |
export async function httpsPost<T>(params: { hostname: string, path: string, headers: Record<string, any>, body?: string }): Promise<{ status: number, data: T | string }> { | |
let {path, hostname, body, headers} = params; | |
let options = { | |
hostname, | |
port: 443, | |
path, | |
method: 'POST', | |
headers | |
} | |
return new Promise((resolve, reject) => { | |
const r = https.request(options, res => { | |
let data = "" | |
res.on('data', (d) => { | |
data += d; | |
}); | |
res.on('end', () => { | |
const status = res.statusCode || 500; | |
resolve({status, data: status === 200 ? JSON.parse(data) : data}); | |
}); | |
}).on('error', error => { | |
reject(error); | |
}); | |
if (body) { | |
r.write(body); | |
} | |
r.end(() => { | |
}) | |
}); | |
} | |
export async function httpsGet<T>(url: string): Promise<{ status: number, data: T | string }> { | |
return await new Promise((resolve, reject) => { | |
https.get(url, (res) => { | |
let data = "" | |
res.on('data', (d) => { | |
data += d; | |
}); | |
res.on('end', () => { | |
const status = res.statusCode || 500; | |
resolve({status, data: status === 200 ? JSON.parse(data) : data}); | |
}) | |
}).on('error', (e) => { | |
reject(e); | |
}); | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment