HTTP requests and Websockets

HTTP requests

fetch API

provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline such as requests and responses.

The fetch() method

Provides an easy and logical way to fetch resources asynchronously across the network

Way easier than (old) XMLHttpRequest

Returns a Promise object

The fetch() method

fetch('http://localhost:3000/tv-shows')
  .then(response => {
    // collection of TV Shows (Array)
    return response.json()
  })
  .then(tvShows => {
    console.log(tvShows);
  });

Making a fetch request (GET)

Use of .then() because fetch() returns a Promise

Use of .json() to extract the JSON content from the HTTP response

async function fetchTVShows() {
  const response = await fetch('http://localhost:3000/tv-shows');
  const tvShows = response.json();
  console.log(tvShows);
}

Making a fetch request (GET)

Using async / await ?

fetch('http://localhost:3000/tv-shows')
  .then(response => {
    return response.json();
  }, err => {
    // Network error, server could not be reached
    console.log(err);
  });

Handling errors

fetch() only rejects a Promise when a network error is encountered

Can't be used to handle 404, 500, ... errors

fetch('http://localhost:3000/tv-shows')
  .then(response => {
    if (response.status === 404 || response.status === 500) {
      console.error(response.statusText);
    } else {
      return response.json();
    }
  })
  .then(tvShows => {
    console.log(tvShows);
  });

Handling errors

Handling HTTP response errors (1/3)

fetch('http://localhost:3000/tv-shows')
  .then(response => {
    if (!response.ok) {
      throw Error(response.statusText);
    }
    return response.json();
  })
  .then(tvShows => {
    console.log(tvShows);
  })
  .catch(err => {
    console.error(err);
  });

Handling errors

Handling HTTP response errors (2/3)

function handleErrors(response) {
  if (!response.ok) { throw Error(response.statusText); }
  return response;
}

fetch('http://localhost:3000/tv-shows')
  .then(handleErrors)
  .then(tvShows => console.log(tvShows))
  .catch(err => console.error(err));

Handling errors

Handling HTTP response errors (3/3)

This way, HTTP response errors use Promise rejection

function postData(url, data) {
  return fetch(url, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(data)
  })
  .then(response => response.json());
}

const newTvShow = { title: 'Silicon Valley' };
postData('http://localhost:3000/tv-shows', newTvShow)
  .then(addedTvShow => console.log(addedTvShow));

Request options

Making a POST request

function putData(url, data) {
  return fetch(url, {
    method: 'PUT',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(data)
  });
}

const updatedTvShow = { id: 1, title: 'Silicon Valley' };
putData('http://localhost:3000/tv-shows/1', updatedTvShow)
  .then(response => console.log(response.status)); // 204

Request options

Making a PUT request

function deleteData(url, data) {
  return fetch(url, { method: 'DELETE' });
}

deleteData('http://localhost:3000/tv-shows/1')
  .then(response => console.log(response.status)); // 204

Request options

Making a DELETE request

And if I can't use fetch()?

If fetch API is not available, you can use axios

axios is a Promise based HTTP for the browser AND node.js

$ npm install axios

Full documentation 👇

Websockets

Websockets

👉 A Websocket is a computer communications protocol

➡️ It enables interaction between a web client and a web server

➡️ Real time data transfer from and to the server

➡️ Both client and server can push data when needed

Websockets

Websockets

Websockets, how to?

Example with socket.io

$ npm install socket.io

Full documentation 👇

Websockets, how to?

On the server side (example with socket.io)

const express = require('express');
const app = express();

// Create Express HTTP server
const server = require('http').createServer(app);
// Create Websocket
const io = require('socket.io')(server);

server.listen(3000, () => {
  console.log('Listening on port 3000...');
});

Websockets, how to?

On the server side (example with socket.io)

io.on('connection', socket => {
  console.log('A user is connected!');
  socket.on('disconnect', () => {
    console.log('A user is disconnected!');
  });
});

Monitoring `connection` and `disconnect` events

A connection is opened when a user / client (browser) connects to the server

Websockets, how to?

On the server side (example with socket.io)

io.on('connection', socket => {
  socket.on('message/new', message => {
    console.log(`Message received: ${message}`);
  });
});

Receiving a custom message from a client

Websockets, how to?

On the server side (example with socket.io)

io.on('connection', socket => {
  socket.emit('hello', 'Hello, World!');
});

Sending a private custom message to a client

(Only the socket that has connected will receive it)

Websockets, how to?

On the server side (example with socket.io)

io.on('connection', socket => {
  socket.broadcast.emit('hello', 'Hello, World!');
});

Sending a custom message to everyone except the current client

(All connected sockets except the current one will receive it)

Websockets, how to?

On the server side (example with socket.io)

io.on('connection', socket => {
  io.emit('hello', 'Hello, World!');
});

Sending a custom message to everyone

(All connected sockets will receive it)

Websockets, how to?

On the client side (example with socket.io)

<script src="/socket.io-client/dist/socket.io.js"></script>
<script>
  // Open connection
  const socket = io.connect('http://localhost:3000');

  // Handle 'hello' event / message
  socket.on('hello', message => {
    console.log(`Message received from server: ${message}`);
  });
</script>

Receiving a custom message from server

Websockets, how to?

On the client side (example with socket.io)

<script src="/socket.io-client/dist/socket.io.js"></script>
<script>
  const socket = io.connect('http://localhost:3000');

  socket.on('hello', message => {
    socket.emit('message/new', { message: 'Hey, there!' });
  });
</script>

Sending a custom message to server

HTTP and Websockets

By Nicolas Payot

HTTP and Websockets

  • 1,152