diff --git a/public/index.html b/public/index.html index b85ca34c0e2239eec9fb3cbd329110621d6cfc4d..00410ada86402fe858a1f0874c6df9ef8e0b70b8 100644 --- a/public/index.html +++ b/public/index.html @@ -7,7 +7,7 @@ function getUsingXMLHttpRequest(){ let xhttp = new XMLHttpRequest(); xhttp.onload = () => { - document.getElementById('1').innerHTML = xhttp.responseText + document.getElementById('1').innerHTML = JSON.parse(xhttp.responseText).counter } xhttp.open('GET', '/counter', true); xhttp.send(); @@ -16,31 +16,37 @@ function postUsingXMLHttpRequest(){ let xhttp = new XMLHttpRequest(); xhttp.onload = () => { - document.getElementById('2').innerHTML = xhttp.responseText + console.log(xhttp.responseText) + document.getElementById('2').innerHTML = JSON.parse(xhttp.responseText).counter } xhttp.open('POST', '/counter', true); - xhttp.send(); + xhttp.setRequestHeader("Content-Type", "application/json"); + xhttp.send(JSON.stringify({'add' : 1})); } function getUsingFetch(){ fetch('/counter', { method: 'GET'}).then( resp => { - resp.text().then( text => { - document.getElementById('3').innerHTML = text + resp.text().then( data => { + document.getElementById('3').innerHTML = JSON.parse(data).counter }) }) } function postUsingFetch(){ - fetch('/counter', { method: 'POST'}) - .then( resp => { - return resp.text() + fetch('/counter', { + method: "POST", + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({'add': 1}) }) - .then( text => { - document.getElementById('4').innerHTML = text + .then( resp => resp.json() ) + .then( data => { + document.getElementById('4').innerHTML = data.counter }) } - - window.addEventListener('load', function() { + + window.addEventListener('load', () => { getUsingXMLHttpRequest() postUsingXMLHttpRequest() getUsingFetch() diff --git a/server.js b/server.js index 261e55ecc2104290c4952f818ffed4e538dbd9ae..274e7af078e94757fe392068713174a376836488 100644 --- a/server.js +++ b/server.js @@ -2,18 +2,23 @@ const express = require('express') let app = express() app.use(express.static('public')) +// Parses all incoming messages of type "application/json" (i.e. body of requests will +// appear to be JSON by default) +app.use(express.json()) let counter = 0; app.route('/counter') .get((req, res) => { res.status(200) - res.send(`Count: ${counter}`) + res.setHeader('Content-Type', 'application/json') + res.json({ counter }) // short form of { 'counter': counter } }) .post((req, res) => { + counter += req.body['add']; res.status(300) - counter++ - res.send(`Count: ${counter}`) + res.setHeader('Content-Type', 'application/json') + res.json({ counter }) // short form of { 'counter': counter } }) app.listen(3000, () => {