我对前端和后端开发相当陌生。尝试使用 React / Node.js 构建一个小型网络,尝试从 Pokemon API 获取数据:https ://pokeapi.co/
我正在尝试获取(使用 axios)所有口袋妖怪的 ID、名称、类型、图片然后渲染它。我取回了所有数据,但是在渲染它时,它只能渲染第一个数据。带有错误信息
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:371:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
.....
代码:
router.get('/', async function (req, res, next) {
const pokemonUrl = 'https://pokeapi.co/api/v2/pokemon?limit=10';
var pokemonPic = [];
var pokemons = [];
// a nest fetch (aixos) data
await axios({
method: 'get',
url: pokemonUrl,
timeout: 10000
})
.then((all) => {
// store data and give access for all
let { data } = all;
// fetch pokemon infomation from each url
data.results.forEach(function (pokemon) {
// the second url to fecth data
const urll = pokemon.url;
axios({
method: 'get',
url: urll,
timeout: 10000
})
.then((respon) => {
// otherwise have no access to respon
let { data } = respon;
var pokeTypes = [];
let pokeName = data.name;
let pokeID = data.id;
let pokePic = data.sprites.front_default;
// pokemon types
for (var i = 0; i < data.types.length; i++) {
pokeTypes += data.types[i].type.name + ' '
}
// check the outcome
console.log(pokeID, pokeName, pokeTypes, pokePic);
// render index from view
res.render('index', {
pokePic,
name: pokeName,
pokeTypes: pokeTypes,
pokeID
})
// return pokeID, pokeName, pokeTypes, pokePic;
})
.catch((error) => {
console.log(error);
})
})
})
任何提示都会有所帮助。热烈感谢。