您好,我是新手的网站开发。我有三个文件: index.html、myscript.js和server.js。index.html上的按钮调用myscript.js中的messageServer函数,该函数将XMLHttpRequest发送到在节点上运行Express的server.js。服务器收到请求,但myscript.js格式的响应始终为空。readyState先是1,然后是4。为什么是null?提前感谢
编辑:响应状态码为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();
}
和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);
https://stackoverflow.com/questions/50778178
复制相似问题