Skip to content

Instantly share code, notes, and snippets.

@sabljakovich
Created March 10, 2019 10:18
Show Gist options
  • Save sabljakovich/7b977e5366f8b6848e0a30a3c3fd53f0 to your computer and use it in GitHub Desktop.
Save sabljakovich/7b977e5366f8b6848e0a30a3c3fd53f0 to your computer and use it in GitHub Desktop.
Node.js native way of performing http post requests.
const http = require('http'); // or https
const defaultOptions = {
host: 'example.com',
port: 80, // or 443 for https
headers: {
'Content-Type': 'application/json',
}
}
const post = (path, payload) => new Promise((resolve, reject) => {
const options = { ...defaultOptions, path, method: 'POST' };
const req = http.request(options, res => {
let buffer = "";
res.on('data', chunk => buffer += chunk)
res.on('end', () => resolve(JSON.parse(buffer)))
});
req.on('error', e => reject(e.message));
req.write(JSON.stringify(payload));
req.end();
})
// Example usage
exports.handler = async (event, context) => new Promise( async (resolve, reject) => {
const token = await post("/auth/login", { username:"test@test.com", password: "password" });
//...
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment