0

First, my javascript code as follows.

var $ = require('jquery');

var url_path = "http://192.168.1.232:9000/get";
$.ajax({
    type: "GET",
    url: "http://192.168.1.232:9000/get?callback=?",
    dataType: 'jsonp',
    async: true,
    error: function () {
       alert("Error is occured...");
    },
    success: function(data) {
        console.log("send to cli cuccessfully!!!");
    }
});

But when I type 'node server.js' on terminal, the error occured saying "$.ajax is not a function". Then I found the solution to handle this by adding

<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

But I have javascript file only, how can I solve this issue?

jny
  • 1
  • 1
  • Here's people explaining how to use jQuery on NodeJS: https://stackoverflow.com/questions/1801160/can-i-use-jquery-with-node-js – Michael Beeson May 20 '18 at 10:07
  • From the [npm jquery package documentation](https://www.npmjs.com/package/jquery): _"For jQuery to work in Node, a window with a document is required. Since no such window exists natively in Node, one can be mocked by tools such as [jsdom](https://github.com/tmpvar/jsdom)."_ – blex May 20 '18 at 10:09
  • Thanks for your help!!! I solved this issue :) – jny May 20 '18 at 10:26

1 Answers1

0

For jQuery to work in Node, a window with a document is required. Since no such window exists natively in Node, one can be mocked by tools such as jsdom. This can be useful for testing purposes.

require("jsdom").env("", function(err, window) {
  if (err) {
    console.error(err);
    return;
  }
  var $ = require("jquery")(window);

  $.ajax({
    url: "uuu",
    type: "GET",
    data: null,
    dataType: "json",
    success: function() {
      console.log("success!")
    },
    error: function() {
      console.log("error")
    }
  });
});

Source

Saeed
  • 5,413
  • 3
  • 26
  • 40
  • Thanks!! And this code needs some modification that "require('jsdom')" should be changed to "require('jsdom/lib/old-api')" :) – jny May 20 '18 at 10:28