我有一个前端和一个服务器后端,我向后端发送一个请求来获取一些图书信息。然后后端调用一个API来获取这些信息,并将其返回给前端。在第一次请求时,一切正常。如果我从前端再发出一个请求,就会产生下面的错误。
我怎样才能做到这一点,使它有可能不断提出一个新的要求,从前端?
node:internal/errors:478
ErrorCaptureStackTrace(err);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:387:5)
at ServerResponse.setHeader (node:_http_outgoing:644:11)
at ServerResponse.header (/Users/jeff/Documents/myProject/backend/node_modules/express/lib/response.js:794:10)
at ServerResponse.send (/Users/jeff/Documents/myProject/backend/node_modules/express/lib/response.js:174:12)
at ServerResponse.json (/Users/jeff/Documents/myProject/backend/node_modules/express/lib/response.js:278:15)
at file:///Users/jeff/Documents/myProject/backend/controllers/model.js:22:14
at file:///Users/jeff/Documents/myProject/backend/controllers/model.js:63:10
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...
showBooks
是来自前端的剩余呼叫的入口点。
export const showBooks = async (req, res) => {
const books = req.body.books;
await getBooksInfo(books, (err, results) => {
if (err) {
res.send(err);
} else {
res.json(results);
}
});
}
然后调用getBooksInfo
,循环遍历所提供的书籍
const getBooksInfo = async (books, result) => {
let all_books = [];
books.forEach(async (book) => {
if (book.type == "adventure") {
const on_sale = book.meta.sale;
if (on_sale == true) {
let book_authors = book.meta.authors;
try {
for (const i in book_authors) {
await book_api(book_authors[i].name, (err, results) => {
if (err) {
console.log(err);
} else {
all_books.push(results);
}
});
}
} catch (err) {
console.log(err);
}
}
result(null, { input: all_books });
}
});
}
book_api
负责获取有关外部静止点的信息
export const book_api = async (author_name, result) => {
try {
const response = await axios.get(`https://book-service.com?author=${author_name}`);
const author_info = response.data.author;
let author = {
"name" : author_info.name,
"website" : author_info.website,
};
result(null, author);
} catch (err) {
result(err, null);
}
};
2条答案
按热度按时间bfrts1fy1#
请注意,
forEach
不适用于异步操作,请尝试将books.forEach(async (book) => ...
替换为for (const book of books)...
u3r8eeie2#
请注意,如果有
console.log(err)
,也要放置return type
,这样一旦请求完成,它就会返回一些结果(true或false)。