Node.js request 模块
Node.js 示例大全Node.js Try Catch
Node.js request 模块
获取请求获取请求是那些请求站点提供指定资源或某些数据的请求。
在此Node.js教程中,我们将学习如何使用请求模块从Node.js中的HTTP Web服务器处理对其他网站的“获取请求”。
使用请求Node.js模块处理获取请求Node.js有一个名为“request”的模块,它可以帮助我们向另一个网站发出请求。我们将从安装Node.js request模块开始。
安装“request” Node.js模块打开终端或命令提示符,然后运行以下命令以安装请求Node.js模块
$npm install request Node.js Get 请求的示例以下是一个示例Node.js文件,其中将包含请求模块。并请求获取资源“ http://www.google.com”。作为第二个参数提供的回调函数接收error(if any),响应和正文。
serverGetRequests.js// 使用请求Node.js模块处理获取请求的示例
// 引入request模块
var request = require("request");
//对资源“http://www.google.com" 发出get请求
request("http://www.google.com",function(error,response,body)
{
console.log(response);
});在终端中运行上面的Node.js文件,如下所示
$node serverGetRequests.js 响应将回显到控制台。
如果用GET请求没有错误,内容错误是零。此信息可用作检查对资源的获取请求中是否存在任何错误。
Node.js Get请求接收错误的示例在某些情况下,我们可能会为资源获取“获取请求”时出错。以下示例是这种情况,其中提供的URL错误。
serverGetRequestsError.js
// 包含请求模块
var request = require("request");
// make a get request for the resource "http://www.go1411ogle.com"
request("http://www.go1411ogle.com",function(error,response,body)
{
console.log(error);
});终端输出
$ node serverGetRequestsError.js
{ Error: getaddrinfo ENOTFOUND www.go1411ogle.com www.go1411ogle.com:80
at errnoException (dns.js:53:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:95:26)
code: 'ENOTFOUND',
errno: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'www.go1411ogle.com',
host: 'www.go1411ogle.com',
port: 80 }结论:在本Node.js教程中,我们学习了如何使用请求模块从Node.js中的HTTP Web服务器处理对其他网站的“获取请求”。
Node.js 示例大全Node.js Try Catch