我正在努力将图片发布到Google Vision API,并返回图片所包含的标签。
我正在使用express.js和Google Cloud Vision模块,但我无法根据Google Vision API的结果创建承诺。当我将图像发布到API时,它将返回一个标签数组。如何确保在运行vision API帮助程序函数之后,我将这些结果存储起来并将其返回到我的反应前端?
Server.js
const express = require('express');
const bodyParser = require('body-parser')
const path = require('path');
const app = express();
const multer = require('multer');
const upload = multer({ dest: './uploads' });
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname)
}
})
const google = require('../helpers/googleVisionAPI.js');
//Hitting file limits on size, increased to 50mb
app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));
app.use(require('express-promise')());
app.post('/upload', upload.single('image'), (req, res) => {
google.visionAPI(req.file.path).then(labels => {
//SEND LABELS BACK TO REACT FRONTEND
console.log(labels);
res.send(labels);
})
});
app.listen(8080);
GoogleVisionAPI.js帮助
// Imports the Google Cloud client library
const vision = require('@google-cloud/vision');
// Creates a client
const client = new vision.ImageAnnotatorClient();
let visionAPI = function(image) {
client
.labelDetection(image)
.then(results => {
// Pull all labels from POST request
const labels = [];
results[0].labelAnnotations.forEach(function(element) {
labels.push(element.description);
});
return labels;
})
// ERROR from Cloud Vision API
.catch(err => {
console.log(err);
res.end('Cloud Vision Error:' , err);
});
}
exports.visionAPI = visionAPI;
有人可以运行Vision API,然后将返回的结果存储到标签变量中,以便发送回我的反应前端吗?
答案 0 :(得分:0)
您的GoogleVisionAPI.js
可缩短为:
// Imports the Google Cloud client library
const vision = require('@google-cloud/vision');
// Creates a client
const client = new vision.ImageAnnotatorClient();
exports.visionAPI = async (filePath) => {
const results = await client.labelDetection(filePath)
const labels = results[0].labelAnnotations.map(element => element.description)
return labels
}
然后你向助手打电话的Server.js
可以是:
app.post('/upload', upload.single('image'), async (req, res) => {
const labels = await google.visionAPI(req.file.path);
console.log(labels)
res.json(labels)
});
错误处理已被省略,应该委托给error handling middleware。
以上代码未经测试。