2013-09-21 3 views
1

내 노드 js 파일에서 jquery를 사용하려고합니다. 이미 jquery 모듈을 설치했습니다. 내가 페이지를 방문 할 때노드 js에서 jquery를 사용하는 방법은 무엇입니까?

, 다음과 같은 에러가 발생합니다

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) 

코드 :

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 + '/'); 

사람이이 문제를 해결하는 방법을 알고 있나요?

감사합니다.

답변

4

업데이트 : 최신 버전의는 (> = 2.1.0), 인스턴스는 다르게 수행하고 이제 jsdom 필요합니다 : 당신은 제대로 jQuery 오브젝트를 인스턴스화되지

var env = require('jsdom').env; 
var html = '<html>...</html>'; 

env(html, function(err, window) { 
    console.log(err); 

    var $ = require('jquery')(window); 
}); 

. 이 그것을 할 방법입니다 :이 작동하지 않습니다

$.getJSON('/resource.json', function() { 
    console.log('success'); 
}) 
    .done(function() { 
    console.log('second success'); 
    }) 
    .fail(function() { 
    console.log('error'); 
    }) 
    .always(function() { 
    console.log('complete'); 
    }); 
+2

:

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

그런 다음 당신은 당신이 당신에게 원하는 방법을 사용할 수 있습니다. 'TypeError : jquery.create가 함수가 아닙니다 .' – corysimmons

+0

원래 답변은 2013 년에 게시되었으며 최신 버전에는 적용되지 않습니다. 업데이트 된 예제를 추가했습니다. – hexacyanide

+0

고맙습니다. 나는 이미 나의 목적을 위해/cheerio를 요청했지만, 빠른 응답/수정에 감사한다. :) – corysimmons

관련 문제