记录下来,方便下次使用。
复制下来可以直接使用。
用到的依赖如下:
- request
- url
- crypto
1 /** 2 * 文件说明:阿里云人脸比对API封装 3 */ 4 5 var request = require('request'); 6 var url = require('url'); 7 var crypto = require('crypto'); 8 var date = new Date().toUTCString() 9 10 ///////////////////////////////////////////////////////////////////////// 11 /** 12 * 配置信息 13 * ak_id :阿里云控制台获取的AccessKey 14 * ak_secret :阿里云控制台获取的AccessKeySecret 15 * Api_Url :阿里云控制台获取Api接口地址 16 */ 17 // AccessKey 18 var ak_id = ''; 19 // AccessKeySecret 20 var ak_secret = ''; 21 // APIURL 22 var Api_Url = '' 23 24 /** 25 * 读取本地图片并转base64编码 26 */ 27 // 图片1 28 var fs = require("fs"); 29 var filePath = "01.jpg"; 30 var imageData = fs.readFileSync(filePath); 31 var imageBase64 = imageData.toString("base64"); 32 //图片2 33 var fs = require("fs"); 34 var filePath = "02.jpg"; 35 var imageData = fs.readFileSync(filePath); 36 var imageBase64_2 = imageData.toString("base64"); 37 38 var options = { 39 url: Api_Url, 40 method: 'POST', 41 body: '{"type": "1", "content_1":"' + imageBase64 + '","content_2":"' + imageBase64 + '"}', 42 headers: { 43 'accept': 'application/json', 44 'content-type': 'application/json', 45 'date': date, 46 'Authorization': '' 47 } 48 }; 49 ///////////////////////////////////////////////////////////////////////// 50 51 52 md5 = function (buffer) { 53 var hash; 54 hash = crypto.createHash('md5'); 55 hash.update(buffer); 56 return hash.digest('base64'); 57 }; 58 59 sha1 = function (stringToSign, secret) { 60 var signature; 61 return signature = crypto.createHmac('sha1', secret).update(stringToSign).digest().toString('base64'); 62 }; 63 64 var body = options.body || ''; 65 var bodymd5; 66 if (body === void 0 || body === '') { 67 bodymd5 = body; 68 } else { 69 bodymd5 = md5(new Buffer(body)); 70 } 71 72 var stringToSign = options.method + "\n" + options.headers.accept + "\n" + bodymd5 + "\n" + options.headers['content-type'] + "\n" + options.headers.date + "\n" + url.parse(options.url).path; 73 74 var signature = sha1(stringToSign, ak_secret); 75 var authHeader = "Dataplus " + ak_id + ":" + signature; 76 options.headers.Authorization = authHeader; 77 78 // 封装函数 79 function AliFace(options) { 80 let promise = new Promise(function (resolve, reject) { 81 request(options, (error, response, body) => { 82 // 失败 83 if (error) { 84 console.log("error", error) 85 reject() 86 } 87 console.log("step4-response body:", response.statusCode, body) 88 console.log(typeof (body)) 89 // 成功 90 // 注意:这里的body是string类型 91 resolve(body) 92 }) 93 }) 94 return promise; 95 } 96 97 98 99 /** 100 * 调用接口进行测试 101 */ 102 AliFace(options).then( 103 function (res) { 104 console.log(res) 105 } 106 )