问题描述
我的问题是如何在从 GET 方法发送数据库信息之前等待信息保存在 Mongoose 数据库中。以上数据保存在POST方法中,GET方法在POST方法之外完成。
问题是GET方法中的console.log出现在console.log之前,检查数据是否保存。
这是我的代码:
// Variables needed to access the API
const API_url = "https://www.googleapis.com/books/v1/volumes?q=isbn:";
const API_key = process.env.GOOGLE_BOOKS_APIKEY;
// Connection to the Google Books API to retrieve dataObject
app.post('/server',async(req,res)=>{
// receive input send by client side (used it to access pictures from Google Api and also )
dataObject = req.body;
const response_books_api = await fetch(`${API_url}${dataObject.book_entry.isbn}&key=${API_key}`);
try {
const json_books_api = await response_books_api.json();
console.log(json_books_api);
res.send(json_books_api);
console.log(json_books_api.items[0].volumeInfo.imageLinks.thumbnail);
// Save data from the userInput in Mongoose Atlas database
const books = new Books({
book_name: dataObject.book_entry.book_name,subtitle: dataObject.book_entry.subtitle,author: dataObject.book_entry.author,publishing_date: dataObject.book_entry.publishing_date,publishing_house: dataObject.book_entry.publishing_house,isbn: dataObject.book_entry.isbn,collection_data: dataObject.book_entry.collection,description: dataObject.book_entry.description,});
const images = new Images({
imageUrl: json_books_api.items[0].volumeInfo.imageLinks.thumbnail,})
books.save().then(()=>{
console.log('data successfully posted!')
// res.status(201).json({
// message: 'data successfully posted!',// });
}).catch((error)=>{
console.log(error);
// res.status(400).json({
// error: error,// })
});
function send_image(){
images.save().then(()=>{
console.log('data successfully posted!')
// res.status(201).json({
// message: 'data successfully posted!',// });
}).catch((error)=>{
console.log(error);
// res.status(400).json({
// error: error,// })
});
}
} catch (err) {
console.error(err);
}
});
// send the book information from database to get it on the client side
app.get('/server/books',(req,res)=>{
Books.find().then(
(books) =>{
res.status(200).json(books);
}
).catch(
(error) =>{
console.log(error);
res.statut(400).json({
error: error
});
}
);
});
// send the imageURL from database to get it on the client side
app.get('/server/images',res)=>{
Images.find().then(
(images) =>{
res.status(200).json(images);
console.log('ok send')
}
).catch(
(error) =>{
console.log(error);
res.statut(400).json({
error: error
});
}
);
})
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)