我最近開始開發一個Node js應用程序,它使用控制器中的Selenium從網頁中獲取項目列表,並且想要將獲取的項目列表作爲JSON響應返回。返回帶有節點js的對象的列表
exports.read_all_products = function (req, res) {
var driver = new webdriver.Builder().forBrowser('phantomjs').build();
driver.get('https://www.test.com/products?PC=' +req.params.category);
driver.wait(until.elementLocated(By.className('product-slide-all')), 20000, 'Could not locate the element within the time specified');
driver.findElements(By.className("product-slide-all")).then(function (elements) {
var arr = [];
elements.forEach(function (element) {
element.getAttribute("innerHTML").then(function (html) {
const dom = new JSDOM(html);
var obj = new Object();
obj.product_name = dom.window.document.querySelector(".product-name").textContent;
obj.product_code = dom.window.document.querySelector(".product-code").textContent;
obj.price = dom.window.document.querySelector(".product-price").textContent;
arr.push(obj);
});
});
res.json(arr);
});
}
問題是我總是得到一個空的JSON響應,即使項目被添加到數組中。我想知道處理這種情況的正確方法。
謝謝。
你可以嘗試移動你的'res.json(arr);'一個級別? ('});')之前? –
不,然後我得到一個錯誤,說'發送後無法設置標題'。 – Lakmal
哦。在這種情況下,你可以嘗試將你的'res.json(arr);'改寫爲'JSON.parse(JSON.stringify(arr))'? –