我正在使用Lambda Face Recognition and Face Detection API via RapidAPI,目前正在通过其api上传图像。 下面我有2个场景。两者具有相同的内容,但似乎只有一种有效,而另一种却给我一个错误。
我得到的错误如下:
code: 500,
error: 'ERROR: \'NoneType\' object has no attribute \'startswith\''
两者之间的唯一区别是,一个方法从mongo数据库中提取productId和productLink,而另一种方法则进行了硬编码。下面是代码:
//pulled from db and stored in variables
let productId = product._id.toString(); //5d9ca969835e1edb64cf03d5
let productLink = product.ProductLink; //http://localhost:4000/uploads/1570544614486-test.jpg
//insert data into api
//doesn't work
myFaceDetAPI.trainAlbum(productLink, productId);
//works
myFaceDetAPI.trainAlbum("http://localhost:4000/uploads/1570544614486-test.jpg", "5d9ca969835e1edb64cf03d5");
我的功能:
this.trainAlbum = (url, id)=>{
let requestString = "https://lambda-face-recognition.p.rapidapi.com/album_train";
let req = unirest("POST", requestString);
let imgURL = url;
let entryId = id
unirest.post(requestString)
.header("X-RapidAPI-Key", API_KEY)
.attach("files", fs.createReadStream(createPath(imgURL)))//creates file path
.field("album", ALBUM_NAME)
.field("albumkey", ALBUM_KEY)
.field("entryid", entryId)
.end(result => {
console.log(result.body);
});
}
问题:
答案 0 :(得分:0)
我发现,通过前端应用程序上传数据时,会将其保存到数据库中并立即在我的图像路径中搜索尚不存在的图像,因此出现了错误。为了解决这个问题,我创建了一个异步函数,该函数将延迟api调用,以便它可以给我的程序一些时间,将图像保存到图像路径。这是代码:
async function customAsyncFunc(productLink, productId){
console.log(1)
await delay(5000)
console.log(2)
myFaceDetAPI.trainAlbum(productLink, productId)
}
function delay(ms){
return new Promise(resolve=>{
setTimeout(resolve,ms)
})
}
// Defined store route
productRoutes.route('/add').post(function (req, res) {
let product = new Product(req.body);
//save to database
product.save()
.then(product => {
let productId = product._id.toString();
let productLink = product.ProductLink;
res.status(200).json({'Product': 'Product has been added successfully'});
//insert data into api
//delay sending data to api so that image can be stored into filepath first
customAsyncFunc(productLink, productId);
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});