Created
July 20, 2018 16:54
-
-
Save gsrai/737b08795fc01093a1ff13f13d32a670 to your computer and use it in GitHub Desktop.
Using Raw Node JS to send data to a http server
This file contains hidden or 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') | |
const HOSTNAME = 'localhost' | |
const PORT = 3000 | |
const client = () => { | |
const bodyString = JSON.stringify({ | |
username: 'foobar', | |
password: 'Password1' | |
}) | |
const headers = { | |
'Content-Type': 'application/json', | |
'Content-Length': bodyString.length | |
} | |
const options = { | |
host: HOSTNAME, | |
path: '/users/1', | |
port: PORT, | |
method: 'PUT', | |
headers | |
} | |
const callback = (response) => { | |
let str = '' | |
response.on('data', (chunk) => str += chunk) | |
response.on('end', () => console.log(str)) | |
} | |
console.log('sending request') | |
http.request(options, callback).write(bodyString) | |
} | |
const server = http.createServer((req, res) => { | |
console.log('received request') | |
res.statusCode = 200 | |
res.setHeader('Content-Type', 'text/plain') | |
let str = '' | |
res.on('data', (chunk) => str += chunk) | |
res.on('end', () => { | |
console.log(str) | |
res.send(`method ${req.method}, url ${req.url}`) | |
}) | |
}) | |
setTimeout(client, 2000) | |
server.listen(PORT, HOSTNAME, () => { | |
console.log(`Server running at http://${HOSTNAME}:${PORT}`) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment