fetch 和 XMLHttpRequest 的问题

Problems with fetch and XMLHttpRequest

第一件事是我是菜鸟,我知道这一点......也许你认为这是一个重复的问题,但我读了很多关于同一个问题的帖子,但没有人帮助。

我正在尝试开发一个关于工作订单、客户、提供商等的 Web 应用程序...我有一个休息 API 具有连接到数据库的正确路由 (mysql) ,以及 CRUM 方法的逻辑。我仍在处理服务器部分,直到几天前一切都很顺利,因为我先用 Postman 测试了它,然后进行了一些简单的测试,一切都运行良好。

问题是我正在尝试开发我的应用程序的逻辑(真正的逻辑)以访问 json 对象的某些单独元素(API returns一个数组,但这不是问题)。我需要检查并生成这种格式 'number/year' 的工作订单的序列号。我尝试使用 fetch() 和 XMLHttpRequest 来访问数据,但没有任何效果……我无法访问数组的元素,因为我总是出错。

如果我在使用 fetch() 的测试中尝试这个,它可以工作,但如果我在我的 numeroOT() 方法中尝试这个,我不能,我不知道还能做什么,所以我需要帮助。 .. 我要为这件事发疯了!!

这是在我的测试中有效的代码:

describe('TEST logica.js', function () {

  it('Genero el Nº de Orden', async () => {

    var numeroDeOT = laLogica.numeroOT(); //this is the method of my logic I'm testing and it's suposed to do the thing


      //This is the the only code which I could acceed to the json. But this has to go inside the numeroOT() method but only works in the test
      //-------------------------------------------

      var response = await fetch('http://localhost:3000/ots');
      var orden = await response.json();
      var laOrden = orden[orden.length-1]; //the last element/json object of the array
      var elNumero = laOrden.numero_ot; //the element I want to check and generate
      console.log(elNumero);
      //The code to check this element and generate the new one goes down here but that's clear



      //---------------------------------------------

    console.log(numeroDeOT);
    expect(numeroDeOT).to.be.a('String'); //this is to check what my method numeroOT() returns. Usually 'undefined'

  }) //it
}); //describe

我意识到我在我的代码中尝试的这两种方式不可能与节点一起使用(因为我使用的是节点),所以我尝试将这段代码用于我的方法并且它工作得很好而且我终于可以访问我的 JSON 个对象数组了!

var options = {
        host : 'localhost',
        port : 3000,
        path : '/ots', // the rest of the url with parameters if needed
        method : 'GET' // do GET
    };

    var request = http.request(options, function (res) {

        console.log("request received");
        var data = '';
        res.on('data', function (chunk) {
            data += chunk;

        });
        res.on('end', function () {
            console.log(data);

        });
    });
    request.on('error', function (e) {
        console.log(e.message);
    });
    request.end();