【问题标题】:XMLHttpRequest response nullXMLHttpRequest 响应空
【发布时间】: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


【解决方案1】:

主要问题是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"} 的响应。

【讨论】:

  • 是的!就是这样,谢谢。只是一个简单的问题:必须将其添加到节点应用程序中是否正常?是因为我在本地运行还是什么
  • 它不仅适用于节点应用程序,在您的示例中是因为 XmlHttpRequest,这里是完整链接 developer.mozilla.org/en-US/docs/Web/HTTP/CORS ,什么请求使用 CORS?部分应该解释它。即使在我的回答中,我也输入了“”,它应该是您的域/,因此对于您的示例 localhost:8888* 。
猜你喜欢
  • 1970-01-01
  • 2020-08-29
  • 2011-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-04
相关资源
最近更新 更多