2016-09-15 83 views
-1

剛剛安裝了node.js,並且無法發送基本的get請求。我曾經在Chrome/Firefox的控制檯中運行過東西,但想要分支出去。我試圖做的(作爲測試)是向網頁發送獲取請求,並將其打印出來。Node.js JavaScript Basic獲取請求

在Chrome的控制檯,我會做這樣的事情:

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

在Node.js的,我會怎麼做呢?我已經嘗試過需要幾件事情,並拿走了幾個例子,但沒有一個能夠工作。

稍後,我還需要添加參數來獲取和發佈請求,所以如果涉及到不同的內容,您能否展示如何使用參數{「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()); 
    } 
});