直接通过 Node.js 的 axios 库发送 HTTP 请求,先获取 Access Token ,再调用人脸检测接口即可。
Node.js 调用百度人脸识别 API 完整教程
时间:2026-12-05
浏览:243
文章目录
获取 Access Token 与 API 关系
百度 AI 开放平台的所有 API 调用都需要基于 Access Token。该令牌由 API Key 和 Secret Key 生成,有效期通常为 30 天。在代码中,我们先构造请求 URL,使用 axios 发起 POST 请求获取 token,后续的人脸识别请求都将携带此 token。
Access Token 是身份验证的核心凭证。开发者需要在百度 AI 控制台创建应用以获取 API Key 和 Secret Key。获取 token 的过程是标准化的 OAuth 2.0 流程。在实际开发中,建议将 token 缓存起来,避免每次请求都重新获取,以提高效率并减少被限流的风险。如果 token 过期或无效,API 会返回特定的错误码,此时需要重新获取。
实现人脸检测完整程序
以下是一个完整的 Node.js 脚本,包含获取 Token 和调用人脸检测接口的逻辑。请将代码保存为 baidu_face_detect.js,并在同一目录下放置一张测试图片 test.jpg。运行前需安装依赖:npm install axios。确保环境变量中设置了你的 API Key 和 Secret Key,或者直接在代码中替换占位符。
const axios = require('axios');
const fs = require('fs');
// 请替换为你的真实 API Key 和 Secret Key
const API_KEY = 'YOUR_API_KEY';
const SECRET_KEY = 'YOUR_SECRET_KEY';
async function getAccessToken() {
const url = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${API_KEY}&client_secret=${SECRET_KEY}`;
try {
const response = await axios.post(url);
return response.data.access_token;
} catch (error) {
console.error('Failed to get access token:', error.message);
throw error;
}
}
async function detectFace(token, imagePath) {
const base64Image = fs.readFileSync(imagePath).toString('base64');
const url = `https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=${token}`;
const params = {
image: base64Image,
image_type: 'BASE64',
face_field: 'age,gender,beauty'
};
try {
const response = await axios.post(url, params, {
headers: { 'Content-Type': 'application/json' }
});
return response.data;
} catch (error) {
console.error('Face detection failed:', error.response ? error.response.data : error.message);
throw error;
}
}
async function main() {
const token = await getAccessToken();
if (!token) {
console.log('No token obtained.');
return;
}
try {
const result = await detectFace(token, './test.jpg');
console.log('Detection Result:', JSON.stringify(result, null, 2));
} catch (e) {
console.log('Process failed due to error.');
}
}
main();
运行程序后,控制台将输出 JSON 格式的检测结果。如果图片中包含人脸,你会看到 face_list 数组,其中包含每个脸部的 age(年龄)、gender(性别)和 beauty(颜值评分)。如果图片路径错误或没有图片,程序会抛出文件读取异常。如果 API Key 无效,getAccessToken 会失败并打印错误信息。成功时,末行输出详细的检测结果。
该程序先读取本地图片文件,将其转换为 Base64 编码。然后调用百度的人脸检测 API,传入 Base64 数据和 image_type。API 返回 JSON 数据,包含检测到的人脸数量、位置坐标、性别、年龄等信息。如果图片中没有人脸,返回结果中的 face_list 将为空数组。注意处理网络异常和 API 返回的错误码,以便排查问题。
处理多张图片或批量场景
当需要处理多张图片时,应复用已获取的 Access Token,避免重复请求。本节沿用上述程序结构,展示如何遍历图片列表并收集结果。
在实际业务中,往往需要批量处理用户上传的图片。我们可以将单张图片的处理逻辑封装为异步函数,并使用 Promise.all 并行执行,以提高处理速度。需要注意的是,并发请求不要超过 API 的 QPS 限制,否则会被拒绝。对于超大图片,建议先进行压缩或裁剪,以减少传输时间和内存占用。如果某张图片处理失败,不应中断整个流程,而应记录错误并继续处理其他图片。
实用工具推荐
绿化、压缩、噪点和虚拟水印,自由调节做旧程度。
选择画质和输出格式,预览压缩前后的大小。