Nodejs http

From wikinotes
Revision as of 00:30, 5 July 2021 by Will (talk | contribs) (→‎Documentation)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Documentation

http docs https://nodejs.org/docs/latest-v15.x/api/http.html
https docs https://nodejs.org/docs/latest-v15.x/api/https.html
ClientRequest https://nodejs.org/docs/latest-v15.x/api/http.html#http_class_http_clientrequest

Server

const http = require('http');
const server = http.createServer((req, res) => {
  res.statusCode 200;
  res.setHeader('Content-Type', 'text/html');
  res.end('<h1>hello world</h1>')
})

const port = 80;
server.listen(port, () => {
  console.log('server started');
})

Request

Basics

Without Payload

const https = require('https')
const options = {
  hostname: 'domain.com',
  port: 443,
  path: '/employees',
  method: 'GET'
}

const request = https.request(options, response => {
  response.on('data', d => {
    process.stdout.write(d)
  })
})

request.on('error', () => { ... })
request.end()

With Payload

NOTE:

unconfirmed

const https = require('https')
const options = {
  hostname: 'domain.com',
  port: 443,
  path: '/employees',
  method: 'POST'
}

const request = https.request(options, response => {
  response.on('data', d => {
    process.stdout.write(d)
  })
})
request.write('{"foo": "bar"}') // <-- data/payload
request.setHeader('Content-Type', 'application/json');

request.on('error', () => { ... })
request.end()