当前位置: 首页 > 后端技术 > Node.js

使用nodejshttp和https下载远程资源,发布数据

时间:2023-04-03 12:52:52 Node.js

如果经常使用nodejs下载资源(简单的爬虫),可以考虑直接使用nodejs内置的http/https模块。test.mjsimporthttpsfrom'https'importfsfrom'fs'importURLfrom'url'leturlObj=URL.parse(url)https.get({...urlObj,rejectUnauthorized:false,//忽略https安全方法:'GET',//请求方法headers:{referer:'',//如果资源有防盗链,清除该属性},},res=>{//设置编码格式res.setEncoding('binary');letimg=''res.on('data',chunk=>{img+=chunk})res.on('end',chunk=>{//写入本地,(文件名,源文件,编码格式)fs.writeFileSync('./test.jpg',img,"binary");})})postdataimporthttpfrom'http'importURLfrom'url'asyncfunctionpost(url,dataStr){让urlObj=URL.parse(url)returnnewPromise((resolve)=>{constreq=http.request({...urlObj,method:'POST',//请求方法标头:{'Content-Length':dataStr.length,//post必须填写的大小'Content-type':'application/x-www-form-urlencoded',//编码格式referer:url,//如果资源有防盗链,清除该属性},},res=>{//设置编码格式//res.setEncoding('二进制');letdata=''res.on('data',chunk=>{data+=chunk})res.on('end',chunk=>{resolve(data)})})//发送数据req.write(数据链);请求结束();})}