3

I am trying to use jquery in my node js file. I installed the jquery module already.

When I visit the page, I get the error:

 var jqxhr = jquery.$.getJSON( "favs.json", function() { ^ TypeError: Cannot call method 'getJSON' of undefined at Server.<anonymous> at Server.EventEmitter.emit (events.js:98:17) at HTTPParser.parser.onIncoming (http.js:2076:12) at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:120:23) at Socket.socket.ondata (http.js:1966:22) at TCP.onread (net.js:525:27) 

code:

var http = require('http'); var jquery = require('jquery'); var PORT = 3000; http.createServer(function(request, response) { response.writeHead(200, {'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': "*"}); var jqxhr = jquery.$.getJSON( "favs.json", function() { console.log( "success" ); }) .done(function() { console.log( "second success" ); }) .fail(function() { console.log( "error" ); }) .always(function() { console.log( "complete" ); }); }).listen(PORT); console.log('Server running at http://127.0.0.1:' + PORT + '/'); 

Does anyone know how to fix this?

Thanks.

1 Answer 1

5

Update: For recent versions (>=2.1.0), instantiation is done differently and now also requires jsdom:

var env = require('jsdom').env; var html = '<html>...</html>'; env(html, function(err, window) { console.log(err); var $ = require('jquery')(window); }); 

You are not instantiating the jQuery object correctly. This is how it should be done:

var jquery = require('jquery'); var $ = jquery.create(); 

Then you can use the method you want to you:

$.getJSON('/resource.json', function() { console.log('success'); }) .done(function() { console.log('second success'); }) .fail(function() { console.log('error'); }) .always(function() { console.log('complete'); }); 
Sign up to request clarification or add additional context in comments.

4 Comments

This doesn't work. TypeError: jquery.create is not a function
The original answer was posted in 2013 and does not apply to recent versions. I've added an updated example.
Cool thanks. I already moved on to request/cheerio for my purposes, but thanks for the quick response/fix. :)
updated one doesn't work. TypeError: env is not a function

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.