Ajax (Asynchronous JavaScript and XML) is a method for sending and receiving data from a web server. It allows parts of a web page to be updated without reloading the whole page. Ajax isn’t a specific technology, but rather a concept that can be implemented using various methods: XMLHttpRequest, fetch() or libraries like Axios. Although Ajax originally used XML, it uses JSON more commonly nowadays.
// Usage: save this code as server.js and run "node server.js [port]"
importhttpfrom'http';importfsfrom'fs';// Get the port from command-line arguments
constport=process.argv[2]||3000;constrequestListener=(request,response)=>{console.log(request.url)if(request.url==='/'||request.url==='/index.html'){// Serve the index.html file
constfilePath='index.html';fs.readFile(filePath,(err,data)=>{if(err){response.writeHead(500,{'Content-Type':'text/plain'});response.end('Error loading index.html');}else{response.writeHead(200,{'Content-Type':'text/html'});response.end(data);}});}elseif(request.url==='/data1'){// Return text for URL '/data1'
response.writeHead(200,{'Content-Type':'text/plain'});response.end('This is the response for /data1');}elseif(request.url==='/data2'){// Return text for URL '/data2'
response.writeHead(200,{'Content-Type':'text/plain'});response.end('This is the response for /data2');}elseif(request.url==='/data3'){// Return text for URL '/data3'
response.writeHead(200,{'Content-Type':'text/plain'});response.end('This is the response for /data3');}else{response.writeHead(404,{'Content-Type':'text/plain'});response.end('404 Not Found');}};// Create and start the server
constserver=http.createServer(requestListener);server.listen(port,()=>{console.log(`Server is running at http://localhost:${port}`);});
Interactive Demo of fetch(), XMLHttpRequest and Axios#
The following demo showcases three methods for making Ajax requests. Save the code as index.html to the directory that contains server.js.
<!-- Copy this code and save it as "index.html" --><!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"/><metaname="viewport"content="width=device-width, initial-scale=1.0"/><title>Ajax Demo</title><scriptsrc="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script></head><body><h1>Ajax Demo</h1><hr/><h2>Use fetch()</h2><buttononclick="LoadDataFetch('/data1')">Load data 1 (fetch)</button><buttononclick="LoadDataFetch('/data2')">Load data 2 (fetch)</button><buttononclick="LoadDataFetch('/data3')">Load data 3 (fetch)</button><buttononclick="LoadDataFetch('/data4')">Load data 4 (fetch, 404)</button><h2>Use XMLHttpRequest</h2><buttononclick="LoadDataXHR('/data1')">Load data 1 (XHR)</button><buttononclick="LoadDataXHR('/data2')">Load data 2 (XHR)</button><buttononclick="LoadDataXHR('/data3')">Load data 3 (XHR)</button><buttononclick="LoadDataXHR('/data4')">Load data 4 (XHR, 404)</button><h2>Use Axios</h2><buttononclick="LoadDataAxios('/data1')">Load data 1 (Axios)</button><buttononclick="LoadDataAxios('/data2')">Load data 2 (Axios)</button><buttononclick="LoadDataAxios('/data3')">Load data 3 (Axios)</button><buttononclick="LoadDataAxios('/data4')">Load data 4 (Axios, 404)</button><h2>Data</h2><pid="response">No data loaded</p><script>constresponseElement=document.querySelector("#response");// Fetches data using fetch()
constLoadDataFetch=(url)=>{fetch(url).then((response)=>{// Check if the response status is OK (200-299)
if(!response.ok){return`HTTP error: ${response.status}`;}returnresponse.text();// Return the response data as text
}).then((data)=>{// Display the data
responseElement.textContent=data;}).catch((error)=>{// Handle errors, e.g., network issues
responseElement.textContent="Request failed (fetch)";});};constLoadDataXHR=(url)=>{constxhr=newXMLHttpRequest();xhr.open("GET",url);xhr.onreadystatechange=()=>{// Check if the response status is 200
if(xhr.readyState===4&&xhr.status===200){// Display the data
responseElement.textContent=xhr.responseText;}else{responseElement.textContent=`HTTP error: ${xhr.status}`;}};xhr.onerror=()=>{// Handle errors, e.g., network issues
responseElement.textContent="Request failed (XHR)";};xhr.send();};constLoadDataAxios=(url)=>{axios.get(url).then((response)=>{// Display the data
responseElement.textContent=response.data;}).catch((error)=>{// Handle errors, e.g., 404 and network issues
responseElement.textContent=`Request failed (Axios): ${error.message}`;// Offline, 404
});};</script></body></html>
Run node server.js, and visit http://localhost:3000/. The demo provides buttons to load data from different URLs using three methods: fetch(), XMLHttpRequest and Axios. Try clicking the buttons to see how each method handles requests, including error responses.