2016-09-15 2 views
-1

node.js를 설치하기 만하면 기본 요청을 보내는 데 문제가 있습니다. 나는 크롬/파이어 폭스의 콘솔에서 물건을 실행하는 데 사용했지만 밖으로 나가고 싶었어요. 내가 뭘하려고하는지 (테스트로서) 웹 페이지에 요청을 보내고 텍스트를 출력 해보자. 나는 그렇게 할 것입니다 방법, Node.js를에서Node.js JavaScript 기본 요청 받기

$.get("http://stackoverflow.com/questions/1801160/can-i-use-jquery-with-node-js", function(data) { 
console.log($(data).find(".question-hyperlink")[0].innerHTML); 
}); 

: 크롬의 콘솔에서

, 나는 같은 것을 할 것인가? 몇 가지 요구 사항을 시도했지만 몇 가지 예는 없지만 어느 것도 작동하지 않았습니다.

나중에 요청을 가져오고 게시하는 매개 변수를 추가해야하기 때문에 다른 내용이 포함 된 경우 매개 변수 { "dog": "bark"}를 사용하여 요청을 보내는 방법을 보여줄 수 있습니까? JSON { "cat": "meow"}을 반환했다고하면 어떻게 읽습니까?

+4

을 ['http.request()'(https://nodejs.org/dist/latest -v6.x/docs/api/http.html # http_http_request_options_callback) Node.js 코드의 문서 – peteb

+0

링크를 제공해 주셔서 감사합니다! –

+0

또한, [요청 모듈] (https://github.com/request/request)을 사용하면'npm install request '로 설치할 수 있습니다. – jfriend00

답변

1

당신은 request module으로 설치할 수 있습니다

npm install request 

그리고, 다음 Node.js를 코드에서이 작업을 수행 :

const request = require('request'); 

request.get("http://stackoverflow.com/questions/1801160/can-i-use-jquery-with-node-js", function(err, response, body) { 
    if (err) { 
     // deal with error here 
    } else { 
     // you can access the body parameter here to see the HTML 
     console.log(body); 
    } 
}); 

요청 모듈은 선택적 매개 변수의 모든 종류의 지원이로 지정할 수 있습니다 사용자 정의 헤더에서 인증 및 쿼리 매개 변수에 이르기까지 모든 요청에 ​​대한 일부입니다. 문서에서 이러한 모든 작업을 수행하는 방법을 볼 수 있습니다.

DOM을 인터페이스로 사용하여 HTML을 구문 분석하고 검색하려면 cheerio module을 사용할 수 있습니다.

npm install request 
npm install cheerio 

그리고,이 코드를 사용 : 당신은 그냥 읽을 시간이 걸릴해야

const request = require('request'); 
const cheerio = require('cheerio'); 

request.get("http://stackoverflow.com/questions/1801160/can-i-use-jquery-with-node-js", function(err, response, body) { 
    if (err) { 
     // deal with error here 
    } else { 
     // you can access the body parameter here to see the HTML 
     let $ = cheerio.load(body); 
     console.log($.find(".question-hyperlink").html()); 
    } 
});