Nodejs jQuery needs jsdom

后端 未结 5 1086
执笔经年
执笔经年 2021-01-12 17:13
$.getJSON(\'https://api.twitch.tv/kraken/channels/\' + SLoppierKitty7, function(channel) {

if (channel[\"stream\"] == null) { 
    var live =\"no\"

} else {

              


        
相关标签:
5条回答
  • 2021-01-12 17:49

    I encountered the same problem, and it is OK now after I changed the package from require('jQuery') to require('jquery'). It seems that the later package (jquery) use a more recent version of jQuery than the former one (jQuery).

    0 讨论(0)
  • 2021-01-12 17:58

    nothing worked for me from here,

    my jquery version:3.2.1

    jsdom version: 10.1.0 found a solution finally:

    var myHtmlString = 'akkadsf lakuseh alhf lasudfa ls<p></p>';
    
    function jQuery(doc){
        const jsdom = require("jsdom");
        const { JSDOM } = jsdom;
        const { window } = new JSDOM();
        const JQ = require("jquery")(window)(`<html>${doc || ''}</html>`);
    }
    var $ = jQuery;
    // my html string:
    var text = $(myHtmlString).text();
    
    0 讨论(0)
  • 2021-01-12 18:00

    I faced the same issue, and while debugging I came to know about something new.

    When you do -

    npm install jQuery
    

    It installs the jQuery version 1.7.4 to your project.

    And when you do -

    npm install jquery
    

    It installs the jQuery version 3.2.1 to your project.

    The difference between both the command is just the uppercase Q. So if you are getting this error then you are probably using the old version of jQuery.

    You can read more about the first command (the old version) here and about the second command here.

    0 讨论(0)
  • 2021-01-12 18:00

    Yes, it does. jQuery expects the 'window' to be there, which is normally a browser-only object. As such, the window needs to be simulated. That is what jsdom does.

    After including jsdom (npm install jsdom):

    // Load jsdom, and create a window.
    var jsdom = require("jsdom").jsdom;
    var doc = jsdom();
    var window = doc.defaultView;
    
    // Load jQuery with the simulated jsdom window.
    $ = require('jquery')(window);
    

    See the jsdom documentation for more information: https://www.npmjs.com/package/jsdom

    0 讨论(0)
  • 2021-01-12 18:07

    jquery 3.2.1, jsdom 10.1.0. It works.

    const jsdom = require("jsdom");
    const { JSDOM } = jsdom;
    const { window } = new JSDOM(`<!DOCTYPE html>`);
    const $ = require('jQuery')(window);
    
    $('<h1>Hello</h1>').appendTo('body');
    console.log($('h1').text());
    
    0 讨论(0)
提交回复
热议问题