[英]Defining a new promise in express.js
我正在將圖像發布到Google Vision API,並返回圖片包含的標簽。
我正在使用express.js和Google Cloud Vision模塊,但無法從Google Vision API的結果中創建承諾。 當我將圖像發布到API時,它將返回一個標簽數組。 如何確保在視覺API幫助程序函數運行后存儲這些結果並將其返回到我的React前端?
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,然后將返回的結果存儲到label變量中,然后發送回我的React前端嗎?
您的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)
});
錯誤處理已被省略,應委托給錯誤處理中間件 。
上面的代碼未經測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.