Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了node.js – 使用节点请求将Cookie Jar导出为JSON大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
请求文档讨论了使用以下示例从文件导入cookie:
var FileCookieStore = require('tough-cookie-filestore');
// NOTE - currently the 'cookies.json' file must already exist!
var j = request.jar(new FileCookieStore('cookies.json'));
request = request.defaults({ jar : j })
request('http://www.google.com',function() {
  request('http://images.google.com')
})

但是,如评论中所述,它期望cookies.json已经存在.问题是,如果我有一个带有cookie的exsTing jar,我怎么能将它导出到JSON?

解决方法

我不确定你的意思是“如果我有一个带有cookie的exsTing jar”,但这里是我如何使用Nodejs管理持久性cookie.

为了避免FileCookieStore出错,我添加了一段代码来创建json文件(如果它不存在).该文件可以为空,只要它存在:

if(!fs.existsSync(cookiepath)){
    fs.closeSync(fs.openSync(cookiepath,'w'));
}

现在,如果仔细查看FileCookieStore代码,只要cookie发生变化,您就会看到它调用saveToFile方法.这意味着通过将FileCookieStore对象传递给请求模块(使用jar选项,如the request documentation所述),json文件将始终反映cookie的状态.

这是一个完整的例子:

var FileCookieStore = require('tough-cookie-filestore');
var request = require('request');
var fs = require("fs");

var cookiepath = "cookies.json";

// create the json file if it does not exist
if(!fs.existsSync(cookiepath)){
    fs.closeSync(fs.openSync(cookiepath,'w'));
}

// use the FileCookieStore with the request package
var jar = request.jar(new FileCookieStore(cookiepath));
request = request.defaults({ jar : jar });

// do whatever you want
request('http://www.google.com',function() {
    request('http://images.google.com')
});

// the cookies in 'jar' corresponds to the cookies in cookies.json
console.log(jar);

要重新开始,只需删除cookipath文件即可.

大佬总结

以上是大佬教程为你收集整理的node.js – 使用节点请求将Cookie Jar导出为JSON全部内容,希望文章能够帮你解决node.js – 使用节点请求将Cookie Jar导出为JSON所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。