【问题标题】:Node.js JavaScript Basic Get RequestNode.js JavaScript 基本获取请求
【发布时间】:2016-09-15 23:25:10
【问题描述】:

刚刚安装了 node.js,但我无法发送基本的 get 请求。我曾经在 chrome/firefox 的控制台中运行东西,但想分支出来。我想要做的(作为测试)是向网页发送一个获取请求,并让它在上面打印出一些文本。

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

【问题讨论】:

  • 您应该花时间阅读 Node.js 代码中的 http.request() 文档
  • 感谢您的链接!
  • 另外,request module 使您可以使用npm install request 进行安装变得更加容易。

标签: javascript node.js get request


【解决方案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());
    }
});

【讨论】:

    猜你喜欢
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多