Repository navigation
Expand file tree
/
Copy path19-https-post.js
More file actions
77 lines (66 loc) · 1.63 KB
/
Copy path19-https-post.js
File metadata and controls
77 lines (66 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// https.request() POST: Content-Length must be
// set manually, and the body is written with
// req.write() / req.end().
import https from "node:https";
function httpsPost(url, data) {
return new Promise((resolve, reject) => {
const urlObj = new URL(url);
const postData = JSON.stringify(data);
const options = {
hostname: urlObj.hostname,
port: urlObj.port || 443,
path: urlObj.pathname + urlObj.search,
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length":
Buffer.byteLength(postData),
},
};
const req = https.request(
options,
(response) => {
const chunks = [];
response.on("data", (chunk) =>
chunks.push(chunk),
);
response.on("end", () => {
const body =
Buffer.concat(chunks).toString();
if (
response.statusCode >= 200 &&
response.statusCode < 300
) {
resolve(JSON.parse(body));
} else {
reject(
new Error(
`HTTP ${response.statusCode}: ${body}`,
),
);
}
});
},
);
req.on("error", reject);
// Set timeout
req.setTimeout(10000, () => {
req.destroy(
new Error("Request timed out"),
);
});
// Write data and end request
req.write(postData);
req.end();
});
}
// Usage
const newPost = await httpsPost(
"https://jsonplaceholder.typicode.com/posts",
{
title: "My Post",
body: "Content here",
userId: 1,
},
);
console.log("Created:", newPost);