javascript - Azure 认知服务,在未检测到人脸时需要帮助处理错误
问题描述
所以在我的应用程序中,它会分析上传照片的面部并返回结果。但是当它没有检测到任何面孔时,应用程序就会崩溃。我在控制台中收到“TypeError:无法读取未定义的属性'faceAttributes'”。现在我只是重定向回'/',但宁愿在 EJS 中显示一条消息。这是发布请求:
app.post("/", upload.single("file-to-upload"), async (req, res) => {
try {
// Upload image to cloudinary
const result = await cloudinary.uploader.upload(req.file.path);
const imageUrl = result.secure_url;
axios({
method: "post",
url: faceEndpoint,
params: {
returnFaceId: true,
returnFaceAttributes:
"age,gender,headPose,smile,facialHair,glasses," +
"emotion,hair,makeup,occlusion,accessories,blur,exposure,noise",
},
data: {
url: imageUrl,
},
headers: { "Ocp-Apim-Subscription-Key": subscriptionKey },
})
.then(function (response) {
console.log("Status text: " + response.status);
console.log("Status text: " + response.statusText);
console.log(response.data[0]);
res.render("result.ejs", {
data: response.data[0].faceAttributes.emotion,
img: imageUrl,
});
})
.catch(function (error) {
res.redirect('/')
console.log(error);
});
} catch (err) {
console.log(err);
}
})
在我的 EJS 中,我只有一个 UL:
<ul>
<li>Anger: <%= (data.anger * 100).toFixed(1) %>%</li>
<li>Contempt: <%= (data.contempt * 100).toFixed(1) %>%</li>
<li>Disgust: <%= (data.disgust * 100).toFixed(1) %>%</li>
<li>Fear: <%= (data.fear * 100).toFixed(1) %>%</li>
<li>Happiness: <%= (data.happiness *100).toFixed(1) %>%</li>
<li>Neutral: <%= (data.neutral * 100).toFixed(1) %>%</li>
<li>Sadness: <%= (data.sadness * 100).toFixed(1) %>%</li>
<li>Surprise: <%= (data.surprise * 100).toFixed(1) %>% </li>
</ul>
我在 ul.. 之前尝试了许多 if 语句的变体。
<% if(data.length == 0) { %>
<h2> no faces detected </h2>
<% } else { %>
// ul goes here
<% } %>
也分别尝试了所有这些..
if(data[0].faceAttributes) if (data[0].faceAttributes.emotion) if(!data) if(typeof faceAttributes == 'undefined'
我对 EJS 很陌生,并且仍在尝试掌握一些概念,所以我只是不理解某些部分。
解决方案
推荐阅读
- android - 我们需要 PhoneStateListener 或 Broadcast Receiver 还是两者兼而有之?
- javascript - 如何返回对象数组属性的总和而不是它们的双精度?
- excel - 希望修改索引公式以检查第二个变量
- php - Readline 完成选项卡额外空间
- google-apps-script - .searchFiles() 迭代器返回“无效参数:q”错误
- python - 由于类型错误,Pandas 合并无法正常工作
- javascript - TypeScript:如何将属性添加到以字符串为标识符的类中
- asp.net - 使用 foreach 循环将项目动态添加到列表中
- asp.net-core-mvc - RouteData 属性重复
- python - 从 SQL 数据库获取数据后的 Pandas 内存问题