fetch 和 XMLHttpRequest 的问题



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

我正在尝试开发一个关于工作订单、客户、提供商等的 Web 应用程序......我有一个 Rest API,其中包含连接到数据库 (mysql) 的正确路由,以及使用 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

我意识到我在代码中尝试的两种方式不可能将它们与 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();

最新更新