首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >XMLHttpRequest响应为空

XMLHttpRequest响应为空
EN

Stack Overflow用户
提问于 2018-06-10 04:17:18
回答 1查看 3.2K关注 0票数 2

您好,我是新手的网站开发。我有三个文件: index.html、myscript.js和server.js。index.html上的按钮调用myscript.js中的messageServer函数,该函数将XMLHttpRequest发送到在节点上运行Express的server.js。服务器收到请求,但myscript.js格式的响应始终为空。readyState先是1,然后是4。为什么是null?提前感谢

编辑:响应状态码为0

index.html:

代码语言:javascript
复制
<!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

代码语言:javascript
复制
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

代码语言:javascript
复制
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);
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50778178

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档