You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ajax调用restcountries API出现[object Object]404错误如何解决

问题原因

你遇到的404报错是因为直接将API返回的对象类型字段拼接进了HTML字符串,浏览器在解析时会自动把对象转为[object Object]字符串:

  • 给img的src属性赋值了对象,浏览器会把这个字符串当成相对资源路径发起请求,就出现了你看到的本地路径404错误
  • 其余name、languages、currencies字段同样是对象类型,直接拼接也会显示为[object Object],无法正常渲染内容

需要修改的代码点

  1. 国旗字段:data.flags是包含png、svg链接的对象,取data.flags.png作为图片地址
  2. 国家名字段:data.name是包含通用名、官方名的对象,取data.name.common显示通用名称
  3. 语言字段:data.languages是键值对格式的对象,用Object.values()取出所有值后拼接为字符串
  4. 货币字段:data.currencies是嵌套对象,取出每个货币的名称后拼接为字符串

修正后的完整JavaScript代码

const getCountry = function(country){ 
  const btn = document.querySelector(".btn-country");
  const countriesContainer = document.querySelector(".countries");

  const request = new XMLHttpRequest();
  request.open("GET", `https://restcountries.com/v3.1/name/${country}`);
  request.send();

  request.addEventListener("load", function () {
    const [data] = JSON.parse(this.responseText);

    const html = `
    <article class="country">
    <img class="country__img" src="${data.flags.png}" />
    <div class="country__data">
      <h3 class="country__name">${data.name.common}</h3>
      <h4 class="country__region">${data.region}</h4>
      <p class="country__row"><span>👫</span>${(
        +data.population / 1000000
      ).toFixed(1)} people</p>
      <p class="country__row"><span>🗣️</span>${Object.values(data.languages).join(', ')}</p>
      <p class="country__row"><span>💰</span>${Object.values(data.currencies).map(curr => curr.name).join(', ')}</p>
    </div>
  </article>
      `;
    countriesContainer.insertAdjacentHTML("beforeend", html);
    countriesContainer.style.opacity = 1;
  });
}

getCountry('portugal');

内容的提问来源于stack exchange,提问作者mightycode Newton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 02:15:05