简体   繁体   中英

Using jQuery in Node.js

Hi I am new here and hope that I can make myself clear. I've been trying to call(?) jQuery in node.js, but everything I do results a failure. I've been trying to solve this for hours and still stuck hopefully there is someone who can help me with this !

I am trying to fetch some info from twitch using their api. In this case if a streamer is online or offline. When I open the page localy ( without node.js) the jQuery code works fine. However when I try to use node.js it gives errors on this: $.

This is after some research and random trying.. (still new to node.js and jQuery):

` http://imgur.com/a/2nhho

`

Edit: The reason why I am trying to use node.js is to update my website without refreshing. So If someone goes online/offline, he/she should not be forced to refresh.

"When the only tool you have is a hammer, every problem looks like a nail."

In this case, you're trying to use the wrong tool for the job. jQuery is built and optimized specifically for use in a browser environment. While you could force it to work by having a shadow DOM... don't.

If you wanted to use jQuery's selectors and DOM manipulation features, cheerio basically implements that API, but specifically for Node.js/server-side.

However, you sound like you want to use it's ajax() method (or one of it's helpers like post() or get() .

Instead, you should use something built for Node. node-fetch ( https://www.npmjs.com/package/node-fetch ) is an excellent and easy to use option that was designed specifically for Node.js.

Here is a simple example from its documentation:

fetch('https://github.com/')
.then(function(res) {
    return res.text();
}).then(function(body) {
    console.log(body);
});

You first call fetch() with the URL you want. It'll return a Promise with a Response object. From that, you can extract the text() or anything else, and from there you can parse it.

If you need to pass options, call a different method (like POST), etc., you'll just give it an options object as the second parameter to the first call (check out their documentation).

There is a npm module you can use that is based off jsdom .
It will give you a window object. Example:

var express = require('express');
var Window = require('window');
global.window = new Window();
global.document = window.document;
var $ = require('jquery');
var app = express();
function game() {
   $("body").append(`<h1>Hello world!</h1>`);
}
game();
app.get('/', function (req, res) {
    res.send(document.getElementsByTagName('html')[0].innerHTML)
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM