XMLHttpRequest响应为null

时间:2018-06-09 20:17:18

标签: javascript html node.js ajax express

您好,我是网络开发的新手。我有三个文件,index.html,myscript.js和server.js。 index.html上的一个按钮调用myscript.js中的messageServer函数,该函数将XMLHttpRequest发送到运行Express on Node的server.js。服务器接收请求,但myscript.js中的响应始终为null。 readyState变为1然后4.为什么它为空?提前谢谢你 编辑:响应状态代码为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);

1 个答案:

答案 0 :(得分:0)

主要问题是CORS(交叉原始资源共享)未在Express上启用,chrome对CORS有点严格。

在app.get之前输入以下代码以启用cross-origin resource sharing

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

完整的server.js应该如下

var express = require("express");
var app = express();

const port = 8888;
let requestCount = 1;

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });

app.get('/', (req, res, next) => {
    console.log('Received get request ' + requestCount);
    ++requestCount;
    res.send(JSON.stringify({myKey: 'myValue'}));
});

app.listen(port);

然后检查开发者工具的网络标签,您应该看到{"myKey":"myValue"}作为回应。