-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathpost-request.js
More file actions
61 lines (53 loc) · 1.28 KB
/
post-request.js
File metadata and controls
61 lines (53 loc) · 1.28 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
const https = require('https');
function postRequest(body) {
const options = {
hostname: 'reqres.in',
path: '/api/users',
method: 'POST',
port: 443, // 👈️ replace with 80 for HTTP requests
headers: {
'Content-Type': 'application/json',
},
};
return new Promise((resolve, reject) => {
const req = https.request(options, res => {
let rawData = '';
res.on('data', chunk => {
rawData += chunk;
});
res.on('end', () => {
try {
resolve(JSON.parse(rawData));
} catch (err) {
reject(new Error(err));
}
});
});
req.on('error', err => {
reject(new Error(err));
});
req.write(JSON.stringify(body));
req.end();
});
}
exports.handler = async event => {
try {
const result = await postRequest({
name: 'John Smith',
job: 'manager',
});
console.log('result is: 👉️', result);
// 👇️️ response structure assume you use proxy integration with API gateway
return {
statusCode: 200,
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(result),
};
} catch (error) {
console.log('Error is: 👉️', error);
return {
statusCode: 400,
body: error.message,
};
}
};