简体   繁体   English

Node.js JavaScript 基本获取请求

[英]Node.js JavaScript Basic Get Request

Just installed node.js, and I'm having trouble sending basic get requests.刚刚安装了 node.js,我在发送基本的 get 请求时遇到了问题。 I used to run things in chrome/firefox's console but wanted to branch out.我曾经在 chrome/firefox 的控制台中运行过一些东西,但想扩展一下。 What I am trying to do (as a test) is send a get request to a webpage, and have it print out some text on it.我想要做的(作为测试)是向网页发送一个 get 请求,并让它在上面打印出一些文本。

In chrome's console, I would do something like this:在 chrome 的控制台中,我会做这样的事情:

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

In node.js, how would I do that?在 node.js 中,我该怎么做? I've tried requiring a few things and gone off a few examples but none of them worked.我试过要求一些东西并去掉一些例子,但没有一个起作用。

Later on, I'll also need to add parameters to get and post requests, so if that involves something different, could you show how to send the request with the parameters {"dog":"bark"}?稍后,我还需要添加参数来获取和发布请求,所以如果这涉及到不同的东西,你能展示如何使用参数 {"dog":"bark"} 发送请求吗? And say it returned the JSON {"cat":"meow"}, how would I read/get that?并说它返回了 JSON {"cat":"meow"},我将如何读取/获取它?

You can install the request module with:您可以使用以下命令安装请求模块

npm install request

And, then do this in your node.js code:然后在您的 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);
    }
});

The request module supports all sorts of optional parameters you can specify as part of your request for everything from custom headers to authentication to query parameters.请求模块支持各种可选参数,您可以将其指定为请求的一部分,从自定义标头到身份验证再到查询参数。 You can see how to do all those things in the doc.你可以在文档中看到如何做所有这些事情。

If you want to parse and search the HTML with a DOM like interface, you can use the cheerio module .如果您想使用类似 DOM 的界面解析和搜索 HTML,您可以使用cheerio 模块

npm install request
npm install cheerio

And, then use this code:然后,使用此代码:

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