Skip to content

Instantly share code, notes, and snippets.

@gsrai
Created July 20, 2018 16:54
Show Gist options
  • Save gsrai/737b08795fc01093a1ff13f13d32a670 to your computer and use it in GitHub Desktop.
Save gsrai/737b08795fc01093a1ff13f13d32a670 to your computer and use it in GitHub Desktop.
Using Raw Node JS to send data to a http server
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