繁体   English   中英

Node.js JavaScript 基本获取请求

[英]Node.js JavaScript Basic Get Request

刚刚安装了 node.js,我在发送基本的 get 请求时遇到了问题。 我曾经在 chrome/firefox 的控制台中运行过一些东西,但想扩展一下。 我想要做的(作为测试)是向网页发送一个 get 请求,并让它在上面打印出一些文本。

在 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"},我将如何读取/获取它?

您可以使用以下命令安装请求模块

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 模块

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());
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM