【问题标题】:Why is my javascript ajax code returning undefined for the XMLHttpRequest GET response? - running in Node.js为什么我的 javascript ajax 代码返回未定义的 XMLHttpRequest GET 响应? - 在 Node.js 中运行
【发布时间】:2020-07-07 02:38:38
【问题描述】:

我正在尝试执行 GET,将 GET 解析为 json 对象,然后在 POST 中将该对象发回。但是,GET 似乎没有返回任何东西(打印未定义到控制台)我在这里缺少什么? 在 Node.js 中运行

const XMLHttpRequest = 
require("xmlhttprequest").XMLHttpRequest;
const http = new XMLHttpRequest();
const url = 'https://jsonplaceholder.typicode.com/posts';
let response, jsonObject;

// perform GET
http.open("GET", url);
http.send();

// save the text
http.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200){
        response = this.responseText;
        console.log(response);
    }
}

// parse json object
console.log(response);
jsonObject = JSON.parse(response);
console.log(jsonObject);

//Perform POST
http.open("POST", url);
http.send(jsonObject);

【问题讨论】:

  • 虽然我了解了解在 node.js 中发出请求的底层代码/技术的重要性,但请不要头疼并使用 fetch API。有一个不错的小 NPM 包,可以将 Web 标准移植到 node.js

标签: javascript ajax get xmlhttprequest


【解决方案1】:

请查看 mozilla.org 上的以下帮助,网址为 https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest。您可以尝试添加如上所述的事件侦听器以查看响应的进度,然后绑定一个函数来处理响应。这样你就知道你调用 asyn AJAX 请求发生了什么。 - 沙鲁乔拉

【讨论】:

    猜你喜欢
    • 2017-05-19
    • 2016-10-26
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    相关资源
    最近更新 更多