使用jsdom并在每个POST请求变量上更新元素,但不起作用

时间:2017-06-20 17:27:16

标签: node.js jsdom

我遇到了问题,我的响应函数没有更新变量,它从文件中取出一个元素:

发布功能:

app.post("/profile", function(req, res) {
var id = req.body.playerid;
request("https://statsroyale.com/profile/" + id).pipe(fs.createWriteStream('stats.html'));
var wins1 = document.getElementsByClassName('statistics__metricCounter ui__headerExtraSmall statistics__trophyMetric');
var wins = wins1[0].innerHTML;
res.render("profile", {person: id, wins: wins}); });

jsdom.env函数(在开头一次设置文件):

jsdom.env({
file: 'stats.html',
done: function (err, window) {
    GLOBAL.window = window;
    GLOBAL.document = window.document;
}

});

但是,如果我请求其他ID,它会显示旧元素

SRC:

 var express = require("express");
var app = express();
var bodyParser = require('body-parser')
var request = require("request")
var fs = require("fs");
var $ = require("jquery");
var jsdom
try {
  jsdom = require("jsdom/lib/old-api.js"); // jsdom >= 10.x
  const { JSDOM } = jsdom;
} catch (e) {
  jsdom = require("jsdom"); // jsdom <= 9.x
  const { JSDOM } = jsdom;
}
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({
  extended: true
}));
app.set("view engine", "ejs");
app.get("/", function(req, res) {
    res.render("home");
});
app.post("/profile", function(req, res) {
    var id = req.body.playerid;
    jsdom.JSDOM.fromURL("https://statsroyale.com/profile/" + id).then(dom => {
      var wins1 = dom.window.document.getElementsByClassName('statistics__metricCounter ui__headerExtraSmall statistics__trophyMetric');
      var wins = wins1[0].innerHTML;
      res.render("profile", {person: id, wins: wins});
    });
});
app.get("/profile", function(req, res) {
    var id = req.query.playerid;
    res.render("profile", {person: id});
});
app.listen(3000);

1 个答案:

答案 0 :(得分:0)

仅设置jsdom环境一次。您需要使用fs.watchFile()来跟踪文件发生的任何更改,并在每次调用回调时重新初始化环境。此外,您需要确保

var wins1 = document.getElementsByClassName('statistics__metricCounter ui__headerExtraSmall statistics__trophyMetric');
var wins = wins1[0].innerHTML;
res.render("profile", {person: id, wins: wins}); });
在异步pipe完成并使用更新的文件重新初始化jsdom之前,不会调用

更新

更简单,而不是使用从本地HTML文件you can invoke jsdom directly from the URL初始化的全局dom

jsdom.JSDOM.fromURL("https://statsroyale.com/profile/" + id, options).then(dom => {
  var wins1 = dom.window.document.getElementsByClassName('statistics__metricCounter ui__headerExtraSmall statistics__trophyMetric');
  var wins = wins1[0].innerHTML;
  res.render("profile", {person: id, wins: wins});
});