【问题标题】:Problems with fetch and XMLHttpRequestfetch 和 XMLHttpRequest 的问题
【发布时间】:2018-05-21 18:40:18
【问题描述】:

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

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

问题是我正在尝试开发我的应用程序的逻辑(真正的逻辑)以访问 json 对象的某些单独元素(API 返回一个数组,但这不是问题)。我需要检查并生成这种格式“编号/年”的工作订单的序列号。我尝试使用 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

【问题讨论】:

    标签: javascript json xmlhttprequest fetch element


    【解决方案1】:

    我意识到我在代码中尝试的两种方法不可能与 node 一起使用(因为我使用的是 node),所以我在我的方法中尝试了这段代码,它运行良好,我终于可以了访问我的 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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-14
      • 1970-01-01
      • 2011-02-05
      • 1970-01-01
      • 2011-09-29
      • 1970-01-01
      相关资源
      最近更新 更多