Hi I'm new to web development. I have three files, index.html, myscript.js and server.js. A button on index.html calls the messageServer function in myscript.js which sends an XMLHttpRequest to server.js running Express on Node. The server receives the request but the response in myscript.js is always null. The readyState goes 1 and then 4. Why is it null? Thanks in advance
Edit: the response status code is 0
index.html:
<!DOCTYPE html>
<html>
<head>
<title id="title">Page Title</title>
<script src="myscript.js"></script>
</head>
<body>
<h1 id="header">Header</h1>
<form>
<input type="button" value="Message Server" onclick="messageServer();">
</form>
</body>
</html>
myscript.js
function messageServer() {
const xhr = new XMLHttpRequest();
const url = 'http://localhost:8888/';
xhr.responseType = 'json';
xhr.onreadystatechange = () => {
log("Ready state: " + xhr.readyState + ", response: " + xhr.response);
if(xhr.readyState === XMLHttpRequest.DONE) {
return xhr.response;
}
};
xhr.open('GET', url);
xhr.send();
}
and server.js
const express = require('express');
const app = express();
const port = 8888;
let requestCount = 1;
app.get('/', (req, res, next) => {
console.log('Received get request ' + requestCount);
++requestCount;
res.send(JSON.stringify({myKey: 'myValue'}));
});
app.listen(port);