0

I have a problem with jquery in nodejs (jsdom):

[server]

const http = require('http');
const fs = require('fs');
const $ = require('jquery');

const jsdom = require("jsdom");
const { JSDOM } = jsdom;

const main = require('./main');

const dom = new JSDOM(`<!DOCTYPE html><html><body><p>Hello world</p></body>`);

http.createServer(function(request, response){
  response.writeHeader(200, {"Content-Type": "text/html"});
  response.write(dom.serialize());
  response.end();
}).listen(8080);

and

[main]

    $.get('xxx').then(function(xxx) {
    ...

Error:

$ is not defined

I want to have access to the house through jquery Where is the mistake?

1 Answers1

0

The problem is that you are requiring jQuery in the server-side, so your client-side won't know what $ is. To solve this you need to inject jQuery, there are a lot of ways to do that, one of those is using a CDN.

See the code below:

const dom = new JSDOM(`
  <!DOCTYPE html>
  <html>
    <body>
      <p>Hello world</p>
    </body>
    <script src="http://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
    <script>
      // Use jQuery here.
    </script>
  </html>
`);