'use strict';
const host = 'localhost';
const http = require('http'); // VSCode shows 3 dots under "require" and says something about NodeRequire???
const fs = require('fs').promises;
const port = 8000;
const requestListener = function (req, res) {
switch (req.url) {
case "/test_ajax_post_json_sans_form.html": // serve an intial html file
fs.readFile(__dirname + '/test_ajax_post_json_sans_form.html')
.then(contents => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(contents);
})
.catch(err => {
res.writeHead(500);
res.end(err);
return;
});
break
case '/test_ajax_post_json_sans_form.html/ajaxTest1': // receive json, process, then return other json
let body = '';
req.on('data', (data) => {
body += data;
});
req.on('end', () => {
console.log(body); // to show all data has arrived
// here we will check or errors, create a complex return-object, stringify it, and send it back
const objToReturn = {data1: 'Test message from server', data2: 'could be a complex json object'};
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(objToReturn));
});
break
case '/favicon.ico':
// browser will call favicon automatically. This satisfies the request (though its failing
// won't keep the ajax from working).
fs.readFile(__dirname + '/favicon.ico')
.then(contents => {
res.writeHead(200, {'Content-Type': 'image/x-icon'});
res.end(contents);
})
.catch(err => { // lacking favicon will not impact test
res.writeHead(200, {'Content-Type': 'image/x-icon'});
res.end();
});
break
default:
res.writeHead(404);
res.end(JSON.stringify({error:'Resource not found'})); // in production, might load a not-found page here
}
}
const server = http.createServer(requestListener);
server.listen(port,host, () => { // binds the server object to a newtwork address
console.log(`Server is running on http://${host}:${port}. (^c to cancel)`);
});
<!DOCTYPE html><body>
<button type="button" id="idSubmitButton">Sendid="submitButton">Send and then Receive JSON</button>
<br>After clicking the button, the JSON string sent from the browser to the server will show in the console.
<br>Then the JSON response string from the server will replace what is below.
<br><br>
<div id='idDisplay'>id='messageArea'>
innerHTML to replace via ajax
</div>
<script>
'use strict';
async function exchangeJSON() {
idSubmitButtondocument.getElementById('submitButton').disabled = truetrue;
// assure post isn't sent again prior to a response try {
// here can build a complex object could beto builtsend
const testObjToSendobjToSend = {message1: 'Test message from browser', message2: 'could be a complex JSON string'};
const xhrresponse = newawait XMLHttpRequestfetch();'test_ajax_post_json_sans_form.html/ajaxTest1', {
xhr.onreadystatechange = function () { method: 'POST',
if (xhr.readyState == 4 && xhr.status == 200) {body: JSON.stringify(objToSend)
});
// this is where the received responseText can be manipulated to update theif page(response.ok) {
documentconst jsonResponse = await response.getElementByIdjson('idDisplay').innerHTML;
= xhr.responseText; // demonstrate json arrived
// here can parse, update screen, idSubmitButtonetc.disabled
= false // post completed, so enable posting again
document.getElementById('messageArea').textContent = JSON.stringify(jsonResponse);
}
}
xhr.open('POST', 'test_ajax_post_json_sans_form.html/ajaxTest1', true);
//throw new Error('Test error in ExchangeJSON'); // uncomment for testing
xhr.setRequestHeader('Content-Type', 'application/json');
} catch xhr.send(JSON.stringify(testObjToSend)error);
{
}
const idSubmitButton = document.getElementById('idSubmitButton''messageArea');.textContent = error;
idSubmitButton.addEventListener('click', function () { }
exchangeJSONdocument.getElementById('submitButton').disabled ;= false;
}
document.getElementById('submitButton').addEventListener('click',exchangeJSON);
</script>
</body></html>