Created
March 10, 2019 10:18
-
-
Save sabljakovich/7b977e5366f8b6848e0a30a3c3fd53f0 to your computer and use it in GitHub Desktop.
Node.js native way of performing http post requests.
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
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