2016-09-15 96 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()); 
    } 
});