如何解决当DATA保存在mongoose Atlas中时通过GET方法发送数据
我的问题是如何在从 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 举报,一经查实,本站将立刻删除。