请求 - 保证
堕落了!
截止2020年2月11日, request 完全贬值。 预计不会出现新的变化。 事实上,有一段时间没有人登陆。 此套件还因其依赖于 request。 。 。 .
菲伊,这里是 推理 request贬值 (单位:千美元) 备选图书馆列表。 。 。 .
简化的 HTTP 请求客户端的“ 请求” 支持 。 由"青鸟"提供动力.
请求 财务报告和审定财务报表 青鸟 相当棒 但我发现自己采用了同样的设计模式 请求 - 保证增加青鸟动力 .then(...) 请求调用对象的方法。 默认情况下,2xx以外的http响应代码会导致承诺被否决. 这可以通过设置来覆盖 options.simple = false。 。 。 .
还检查一下新的图书馆 非常类似 request-promise 页:1数字 :
request-promise-nativev1 — 不依赖"蓝鸟",而是使用本土ES6承诺.request-promise-anyv1 – 允许您注册由any-promise。 。 。 .
从v3到v4的迁移
request成为同伴依赖。 因此,确保request以直接依赖方式安装到您的项目中。 ()npm install --save request(中文(简体) )- 不再支持继续本地存储。 不过,你 可以获取支持 通过使用
request-promise-any。 。 。 . - 当你迁移你
transform函数到 v3 并需要添加if (!(/^2/.test('' + response.statusCode))) { return resolveWithFullResponse ? response : body; }您现在可以设置选项transform2xxOnly = true换句话说.
从v2到v3的迁移
-
处理
transform函数被大修。 这有两个影响:StatusCodeError.response是改变而不是现在的原反应。 当options.simple实值true(默认). 请更新您的transform功能还包括非-2xx响应的转换. 要得到旧行为,你可以添加if (!(/^2/.test('' + response.statusCode))) { return resolveWithFullResponse ? response : body; }转到您的第一行transform用于请求的函数options.simple === true但是,您可能更喜欢更新您的transform功能可以转换为2xx 以及非2xxx 响应,因为这使其执行与使用simple选项.- 如果变换操作抛出出错误, 请求会以一个
TransformError。 。cause属性包含由变换操作所抛出的错误。 此前,该请求因变换操作所抛出的错误被直接拒绝. 把它包装成一个TransformError使错误处理更容易.
-
蓝鸟从v2更新到v3. 这对大多数案件来说都没什么区别 不过,如果您使用高级承诺链,从请求-承诺返回的承诺开始,请检查 青鸟的新特征和变化。 。 。 .
安装
此模块通过 npm 安装 :
npm install --save request
npm install --save request-promise
request 被定义为对等依赖,因此必须单独安装.
骗局
var rp = require('request-promise');
自兹 request-promise 环绕 request 所有与工作相关的 request 也与 request-promise也检查一下 request 文档 需要更多的实例.
抓取网页
rp('http://www.google.com')
.then(function (htmlString) {
// Process html...
})
.catch(function (err) {
// Crawling failed...
});
抓取一个更好的网页
var cheerio = require('cheerio'); // Basically jQuery for node.js
var options = {
uri: 'http://www.google.com',
transform: function (body) {
return cheerio.load(body);
}
};
rp(options)
.then(function ($) {
// Process html like you would with jQuery...
})
.catch(function (err) {
// Crawling failed or Cheerio choked...
});
从JSON里斯特的API那里拿些东西
var options = {
uri: 'https://api.github.com/user/repos',
qs: {
access_token: 'xxxxx xxxxx' // -> uri + '?access_token=xxxxx%20xxxxx'
},
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
rp(options)
.then(function (repos) {
console.log('User has %d repos', repos.length);
})
.catch(function (err) {
// API call failed...
});
POST 数据为 JSON REST API
设定 option.body 您的数据和 json: true 把尸体编码成JSON HTML 表格见下文.
var options = {
method: 'POST',
uri: 'http://api.posttestserver.com/post',
body: {
some: 'payload'
},
json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(function (parsedBody) {
// POST succeeded...
})
.catch(function (err) {
// POST failed...
});
POST 像 HTML 窗体做
将数据传递给 options.form 以与 HTML 格式相同的方式编码主体:
var options = {
method: 'POST',
uri: 'http://posttestserver.com/post.php',
form: {
// Like <input type="text" name="name">
name: 'Josh'
},
headers: {
/* 'content-type': 'application/x-www-form-urlencoded' */ // Is set automatically
}
};
rp(options)
.then(function (body) {
// POST succeeded...
})
.catch(function (err) {
// POST failed...
});
如果您想要包含文件上传, 请使用 options.formData数字 :
var options = {
method: 'POST',
uri: 'http://posttestserver.com/post.php',
formData: {
// Like <input type="text" name="name">
name: 'Jenn',
// Like <input type="file" name="file">
file: {
value: fs.createReadStream('test/test.jpg'),
options: {
filename: 'test.jpg',
contentType: 'image/jpg'
}
}
},
headers: {
/* 'content-type': 'multipart/form-data' */ // Is set automatically
}
};
rp(options)
.then(function (body) {
// POST succeeded...
})
.catch(function (err) {
// POST failed...
});
包含饼干
var tough = require('tough-cookie');
// Easy creation of the cookie - see tough-cookie docs for details
let cookie = new tough.Cookie({
key: "some_key",
value: "some_value",
domain: 'api.mydomain.com',
httpOnly: true,
maxAge: 31536000
});
// Put cookie in an jar which can be used across multiple requests
var cookiejar = rp.jar();
cookiejar.setCookie(cookie, 'https://api.mydomain.com');
// ...all requests to https://api.mydomain.com will include the cookie
var options = {
uri: 'https://api.mydomain.com/...',
jar: cookiejar // Tells rp to include cookies in jar that match uri
};
rp(options)
.then(function (body) {
// Request succeeded...
})
.catch(function (err) {
// Request failed...
});
得到完整的响应 而不是只是身体
var options = {
method: 'DELETE',
uri: 'http://my-server/path/to/resource/1234',
resolveWithFullResponse: true // <--- <--- <--- <---
};
rp(options)
.then(function (response) {
console.log("DELETE succeeded with status %d", response.statusCode);
})
.catch(function (err) {
// Delete failed...
});
只有在请求因技术原因失败时才能被拒绝
var options = {
uri: 'http://www.google.com/this-page-does-not-exist.html',
simple: false // <--- <--- <--- <---
};
rp(options)
.then(function (body) {
// Request succeeded but might as well be a 404
// Usually combined with resolveWithFullResponse = true to check response.statusCode
})
.catch(function (err) {
// Request failed due to technical reasons...
});
更多选项查看 请求文件。 。 。 .
详细 API
考虑:
- 请求对象
- 与一个 相同的 API数字 :
require('request-promise') == require('request')这么说吧 - 不过, 坚持回应 (例如:.
.pipe(...))为 失踪 因为要求 - 保证会增加 内存足迹 对于大的 要求不必要的高。 使用原始请求库进行此操作 。 您可以在同一项目中使用两个库.
- 与一个 相同的 API数字 :
- 在请求调用对象上加上一些方法 :
rp(...).then(...)或例如:.rp.post(...).then(...)转弯rp(...)财务报告和审定财务报表rp.post(...)成为承诺rp(...).catch(...)或例如:.rp.del(...).catch(...)和蓝鸟承诺一样- 错误
request库将传递到回调由request-promise然后传给捕捉者。 见 代码示例 见下文.
- 错误
rp(...).finally(...)或例如:.rp.put(...).finally(...)和蓝鸟承诺一样rp(...).cancel()或例如:.rp.get(...).cancel()取消请求rp(...).promise()或例如:.rp.head(...).promise()返回基础承诺,以便你能够访问全部 蓝鸟 API
- 加上一些额外的选项:
simple = true用于设定 2xx 以外的状态代码是否也应拒绝承诺的布尔resolveWithFullResponse = false它是一个布尔来决定 承诺是应该通过充分的反应还是仅仅的反应机构来解决transform将响应转换为自定义值,从而实现承诺transform2xxOnly = false它是一个布尔来设定变换函数是适用于所有响应,还是仅适用于有 2xx 状态代码的响应
请求返回对象的电话如下: rp(...) 或例如:. rp.post(...) 是定期承诺/A+遵守承诺,可以被任何兼容的承诺库所同化.
方法 .then(...), (中文(简体) ), .catch(...),以及 .finally(...) - 您可以调用请求的调用对象 - 返回一个完整的蓝鸟承诺。 也就是说你满了 蓝鸟 API 可供进一步连锁使用。 例如: rp(...).then(...).spread(...) 但是,如果您需要一种方法,而不是 .then(...), (中文(简体) ), .catch(...),或 .finally(...) 将会是 首个 在链中,使用 .promise()数字 : rp(...).promise().bind(...).then(...)
.当时(已填入,已拒绝)
// As a Request user you would write:
var request = require('request');
request('http://google.com', function (err, response, body) {
if (err) {
handleError({ error: err, response: response, ... });
} else if (!(/^2/.test('' + response.statusCode))) { // Status Codes other than 2xx
handleError({ error: body, response: response, ... });
} else {
process(body);
}
});
// As a Request-Promise user you can now write the equivalent code:
var rp = require('request-promise');
rp('http://google.com')
.then(process, handleError);
// The same is available for all http method shortcuts:
request.post('http://example.com/api', function (err, response, body) { ... });
rp.post('http://example.com/api').then(...);
. 渔获物(被拒)
rp('http://google.com')
.catch(handleError);
// ... is syntactical sugar for:
rp('http://google.com')
.then(null, handleError);
// However, this:
rp('http://google.com')
.then(process)
.catch(handleError);
// ... is safer than:
rp('http://google.com')
.then(process, handleError);
关于更多信息 .then(process).catch(handleError) 对 .then(process, handleError),参见蓝鸟文件 承诺反攻击。 。 。 .
. 最终(完成)
rp('http://google.com')
.finally(function () {
// This is called after the request finishes either successful or not successful.
});
.cancel () (中文(简体) )
使用此方法取消请求 蓝鸟的取消功能。 。 。 .
何时 .cancel() 称为:
- 约言既不解,也不解脱
- 请求是 已中止。 。 。 .
.承诺() - 用于高级用途
为了不污染 请求调用对象 与基础 蓝鸟承诺的方法 .then(...), (中文(简体) ), .catch(...),以及 .finally(...) 暴露在大多数使用案例。 效果是蓝鸟承诺的任何方法 .then(...), (中文(简体) ), .catch(...),或 .finally(...) 无法用作 首个 承诺链中的方法:
// This works:
rp('http://google.com').then(function () { ... });
rp('http://google.com').catch(function () { ... });
// This works as well since additional methods are only used AFTER the FIRST call in the chain:
rp('http://google.com').then(function () { ... }).spread(function () { ... });
rp('http://google.com').catch(function () { ... }).error(function () { ... });
// Using additional methods as the FIRST call in the chain does not work:
// rp('http://google.com').bind(this).then(function () { ... });
// Use .promise() in these cases:
rp('http://google.com').promise().bind(this).then(function () { ... });
履行诺言 resolveWithFullResponse 选项
// Per default the body is passed to the fulfillment handler:
rp('http://google.com')
.then(function (body) {
// Process the html of the Google web page...
});
// The resolveWithFullResponse options allows to pass the full response:
rp({ uri: 'http://google.com', resolveWithFullResponse: true })
.then(function (response) {
// Access response.statusCode, response.body etc.
});
拒绝承诺 simple 选项
// The rejection handler is called with a reason object...
rp('http://google.com')
.catch(function (reason) {
// Handle failed request...
});
// ... and would be equivalent to this Request-only implementation:
var options = { uri: 'http://google.com' };
request(options, function (err, response, body) {
var reason;
if (err) {
reason = {
cause: err,
error: err,
options: options,
response: response
};
} else if (!(/^2/.test('' + response.statusCode))) { // Status Codes other than 2xx
reason = {
statusCode: response.statusCode,
error: body,
options: options,
response: response
};
}
if (reason) {
// Handle failed request...
}
});
// If you pass the simple option as false...
rp({ uri: 'http://google.com', simple: false })
.catch(function (reason) {
// Handle failed request...
});
// ... the equivalent Request-only code would be:
request(options, function (err, response, body) {
if (err) {
var reason = {
cause: err,
error: err,
options: options,
response: response
};
// Handle failed request...
}
});
// E.g. a 404 would now fulfill the promise.
// Combine it with resolveWithFullResponse = true to check the status code in the fulfillment handler.
有了0.4版本后,原因对象变成了具有相同属性的 Error对象,以确保后向相容性. 这些新的错误类型允许目标捕获区块:
var errors = require('request-promise/errors');
rp('http://google.com')
.catch(errors.StatusCodeError, function (reason) {
// The server responded with a status codes other than 2xx.
// Check reason.statusCode
})
.catch(errors.RequestError, function (reason) {
// The request failed due to technical reasons.
// reason.cause is the Error object Request would pass into a callback.
});
这个 transform 函数
您可以将函数传递给 options.transform 以生成一个自定义的实现值当承诺得到解决时.
// Just for fun you could reverse the response body:
var options = {
uri: 'http://google.com',
transform: function (body, response, resolveWithFullResponse) {
return body.split('').reverse().join('');
}
};
rp(options)
.then(function (reversedBody) {
// ;D
});
// However, you could also do something useful:
var $ = require('cheerio'); // Basically jQuery for node.js
function autoParse(body, response, resolveWithFullResponse) {
// FIXME: The content type string could contain additional values like the charset.
// Consider using the `content-type` library for a robust comparison.
if (response.headers['content-type'] === 'application/json') {
return JSON.parse(body);
} else if (response.headers['content-type'] === 'text/html') {
return $.load(body);
} else {
return body;
}
}
options.transform = autoParse;
rp(options)
.then(function (autoParsedBody) {
// :)
});
// You can go one step further and set the transform as the default:
var rpap = rp.defaults({ transform: autoParse });
rpap('http://google.com')
.then(function (autoParsedBody) {
// :)
});
rpap('http://echojs.com')
.then(function (autoParsedBody) {
// =)
});
第三个 resolveWithFullResponse 变换函数的参数相当于随请求而通过的选项. 这使得可以区分是否只有被转化的正体或整个响应才能被转换函数还原:
function reverseBody(body, response, resolveWithFullResponse) {
response.body = response.body.split('').reverse().join('');
return resolveWithFullResponse ? response : response.body;
}
至于Request-Promise v3,变换功能是ALWAYS针对非-2xx响应执行的. 何时 options.simple 设置为 true (违约)然后以 StatusCodeError。在此情况下,错误包含变换的响应 :
var options = {
uri: 'http://the-server.com/will-return/404',
simple: true,
transform: function (body, response, resolveWithFullResponse) { /* ... */ }
};
rp(options)
.catch(errors.StatusCodeError, function (reason) {
// reason.response is the transformed response
});
准备 options.transform2xxOnly = true 只执行带有2xx状态代码的响应的变换功能。 对于其他状态代码——独立于任何其他设置,例如. options.simple – 变换功能没有执行.
处理错误
如果变换操作失败( 显示出错 ) , 请求将被以 a 拒绝 TransformError数字 :
var errors = require('request-promise/errors');
var options = {
uri: 'http://google.com',
transform: function (body, response, resolveWithFullResponse) {
throw new Error('Transform failed!');
}
};
rp(options)
.catch(errors.TransformError, function (reason) {
console.log(reason.cause.message); // => Transform failed!
// reason.response is the original response for which the transform operation failed
});
对继续当地储存的实验支助
不再支持继续本地存储。 不过,你 可以获取支持 通过使用 request-promise-any。 。 。 .
调试
调试“ 请求保证” 操作的方法是一样的 说明 请求。 它们是:
- 启动节点进程像
NODE_DEBUG=request node script.js(单位:千美元)lib,request,otherlib工作也一样. - 设定
require('request-promise').debug = true任何时候(这与#1相同). - 使用 请求调试模块 以查看请求和答复标题及机构。 文书要求-承诺
require('request-debug')(rp);。 。 。 .
模拟请求 - 保证
通常您想要模拟整个请求函数,该函数由 require('request-promise')。这不可能通过使用像 sinon.js (英语) 一个人 你需要的是一个库,它连接到模块加载器,并确保在测试代码调用时返回您的模拟器 require('request-promise')。 。 。 . 摩克语Name 是这种图书馆之一.
@florianschmidt 1994 (法语). 他的解决方案是:
before(function (done) {
var filename = "fileForResponse";
mockery.enable({
warnOnReplace: false,
warnOnUnregistered: false,
useCleanCache: true
});
mockery.registerMock('request-promise', function () {
var response = fs.readFileSync(__dirname + '/data/' + filename, 'utf8');
return Bluebird.resolve(response.trim());
});
done();
});
after(function (done) {
mockery.disable();
mockery.deregisterAll();
done();
});
describe('custom test case', function () {
// Test some function/module/... which uses request-promise
// and it will always receive the predefined "fileForResponse" as data, e.g.:
var rp = require('request-promise');
rp(...).then(function(data) {
// ➞ data is what is in fileForResponse
});
});
以此为基础,你现在可以建立一个更复杂的模型. 锡农.js 也可能有帮助.
捐款
为建立你的发展环境:
- 复制重播到您的桌面,
- 在壳中
cd到主文件夹, - 击出
npm install, (中文(简体) ), - 击出
npm install gulp -g如果你还没有在全球安装gulp,和 - 运行
gulp dev. (或运行)node ./node_modules/.bin/gulp dev如果你不想在全球安装gulp。)
gulp dev 监视所有源文件, 如果您保存一些更改, 它会插入代码并执行所有测试 。 测试覆盖报告可从下列来源查看: ./coverage/lcov-report/index.html。 。 。 .
如果您想要调试测试, 请使用 gulp test-without-coverage 运行所有测试,而不通过测试覆盖仪表来模糊代码.
更改历史
- v4.2.5 (2019-11-03) (中文(简体) )
- v 4.2.4 (2019-02-14) (中文(简体) )
- 错误设定
tough-cookie版本,现在^2.3.3(多亏了@eforceur指出这一点 - 如果安装
[email protected]请在升级后确保request财务报告和审定财务报表request-promise使用相同的物理副本tough-cookie。 。 。 .
- 错误设定
- v 4.2.3 (2019-02-14) (中文(简体) )
- v4.2.2 (2017-09-22) (中文(简体) )
- 升级
tough-cookie到一个没有regex DoS 弱点的版本 (感谢@rouanw 拉动请求 # 226(中文(简体) )
- 升级
- v4.2.1 (2017-05-07) (中文(简体) )
- v4.2.0 (2017-03-16) (中文(简体) )
- 更新
bluebird改为 v3.5 (感谢@acinader 拉动请求 # 181(中文(简体) )
- 更新
- v 4.1.1 (2016-08-08) (中文(简体) )
- v4.1.0 (2016-07-30) (中文(简体) )
- 已添加取消支持 (感谢@not-an-aardvark为 拉动请求 # 123(中文(简体) )
- v4.02 (2016-07-18) (中文(简体) )
- 用于 Webpack 和浏览器等模块捆绑器的修复
- v4.0.1 (2016-07-17) (中文(简体) )
- 固定
@request/promise-core用于更安全版本的版本
- 固定
- v4.0.0 (2016-07-15) (中文(简体) )
- 中断更改数字 :
request被宣布为对等依赖, 用户现在必须单独安装 - 中断更改: 自此停止对继续本地存储的支持
request-promise-any可能会是 使用过的 现在 - 介绍
transform2xxOnly选项,以缓解关于新的transform在v3.0.0中处理 (感谢@stevage指出 问题131(中文(简体) ) - 已解决的问题 65号 财务报告和审定财务报表 71号 通过出版几乎完全相同的图书馆来支持其他承诺的执行:
request-promise-native财务报告和审定财务报表request-promise-any(感谢@benjamingr,@eilgin,@gillesdemey,@hildjj,@iggycoloma,@jonathanong,@knpwrs,@MarkHerhold,@massimocode,@mikeal,@niftylettuce,@raitucarp,@sher deadlock,@tonylukasavage,和@vgoloviznin的宝贵讨论!) - 持ISC牌照的图书馆
- 中断更改数字 :
- v3.0.0 (2016-04-16) (中文(中国大陆) )
- 中断更改: 更改处理
transform函数 (感谢@Limes解释需要在 问题86(中文(简体) ) - 中断更改翻译:
bluebird改为v3 (感谢您@ BrandonSmith 拉动请求 # 103(中文(简体) ) - 改进
StatusCodeError.message - 更新
lodash改为v4.6 - 改进了在教育、教育、教育、
.catch(...)最佳做法 (感谢@ RebootJeff 拉动请求 # 98(中文(简体) )
- 中断更改: 更改处理
- v2.0.1 (2016-02-17) (中文(简体) )
- 更新
lodash改为v4 (感谢 @ ratson for 拉动请求 # 94(中文(简体) )
- 更新
- v2.0.0 (2016-01-12) (中文(简体) )
- v1.0.2 (2015-10-22) (中文(简体) )
- 删除
continuation-local-storage从同行的依赖性,因为它是不必要的 (感谢@mrhyde 努力寻求更好的解决办法,讨论 问题70(中文(简体) )
- 删除
- v1.0.1(2015-10-14) (中文(简体) )
- 通过标记固定 npm 警告
continuation-local-storage作为同伴依赖
- 通过标记固定 npm 警告
- v1.0.0 (2015-10-11) (中文(简体) )
- 中断更改: 先前同步抛出的一些错误, 如输入参数错误, 现在被传递给被拒绝的许诺 (感谢@josnidhin建议 问题43(中文(简体) )
- 中断更改: Request-Promise不再装入自己的"青鸟"原型. 如果你在项目中使用了"蓝鸟"并修改了原型,那么"请求-保证"可能会在内部使用被修改了的"蓝鸟"原型.
- 对于头部请求,将返回标题而不是空正文(除非
resolveWithFullResponse = true用于) (感谢@zcei提议更改 问题58(中文(简体) ) - 扩展
transform函数 :resolveWithFullResponse参数 - 为继续本地存储增加实验支持 (感谢@ silverbp 准备此文件) 问题64(中文(简体) )
- 将节点.js 4 添加到 Travis CI 大楼
- 更新了读取器 (感谢许多人对问题的反馈) 55号 财务报告和审定财务报表 59号(中文(简体) )
- v.4.3 (2015-07-27) (中文(简体) )
- 减少间接费用,只是需要用到的摇篮功能,而不是整个摇篮库 (感谢@luanmuniz 牵引请求 # 54(中文(简体) )
- 更新的依赖关系
- v.4.2 (2015-04-12) (中文(简体) )
- 更新的依赖关系
- v. 4.1 (2015-03-20) (中文(简体) )
- 在没有 v8 引擎的浏览器中工作的改进错误类型 (感谢@nodiis 拉动请求 # 40(中文(简体) )
- v. 4.0 (2015-02-08) (中文(简体) )
- v. 3.3 (2015-01-19) (中文(简体) )
- 固定处理可能未处理的拒绝 以配合最新版本的"蓝鸟" (感谢@slang800将此事报告给 问题36(中文(简体) )
- v.3.2 (2014-11-17) (中文(简体) )
- 已曝光
.finally(...)允许将它作为承诺链中的第一个方法 (感谢@hjpbarcelos的帮助) 拉动请求 # 28(中文(简体) )
- 已曝光
- v. 3.1 (2014-11-11) (中文(简体) )
- 添加内容
.promise()高级蓝鸟 API 使用方法 (感谢@devo-tox的反馈) 问题27(中文(简体) )
- 添加内容
- v. 3.0 (2014-11-10) (中文(简体) )
- 谨慎地从零开始重写, 使 Request- 保证为 Request 替换一个 滴入
许可证(ISC)
以防你从没听说过 ISC 许可证 它在功能上相当于麻省理工学院的许可.
见 自由文件 详细情况.