【发布时间】:2018-11-19 13:11:56
【问题描述】:
您好,我是网络开发新手。我有三个文件,index.html、myscript.js 和 server.js。 index.html 上的一个按钮调用 myscript.js 中的 messageServer 函数,该函数将 XMLHttpRequest 发送到在 Node 上运行 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);
【问题讨论】:
-
您将响应类型设置为json,为什么还要以字符串形式发送?将其更改为
res.send({myKey: 'myValue'}); -
@kiddorails 我收到这个错误:“TypeError: First argument must be a string or Buffer” 当我这样做时
-
改回旧版本并在其前添加
res.setHeader('Content-Type', 'application/json');。 -
或
res.json({myKey; 'myValue'})应该工作得非常理想 -
都试过了。仍然为空
标签: javascript html node.js ajax express