【问题标题】:Why is my JavaScript API call returning a 400 error?为什么我的 JavaScript API 调用返回 400 错误?
【发布时间】:2018-11-15 22:31:31
【问题描述】:

我有一个 API 调用收到“加载资源失败”400 错误。我尝试删除 cookie 和缓存并使用不同的浏览器。当我看到图像大小可能是问题时,我还删除了图像。我读到了对 HTTP 标头的需求,但不明白它在我的代码中的位置或它的外观。任何帮助将不胜感激!这是我的 JS:

    const app = document.getElementById('root');

    const container = document.createElement('div');
    container.setAttribute('class', 'container');

    app.appendChild(container);

    var request = new XMLHttpRequest();
    request.open('GET', 'https://www.themuse.com/api/public/jobs', true);
    request.onload = function () {

    // Begin accessing JSON data here
    var data = JSON.parse(this.response);
    if (request.status >= 200 && request.status < 400) {
    data.forEach(job => {
    const card = document.createElement('div');
    card.setAttribute('class', 'card');

    const h1 = document.createElement('h1');
    h1.textContent = job.title;

    const p = document.createElement('p');
    job.description = job.description.substring(0, 300);
    p.textContent = `${job.description}...`;

    container.appendChild(card);
    card.appendChild(h1);
    card.appendChild(p);
      });
    } else {
    const errorMessage = document.createElement('marquee');
    errorMessage.textContent = `Darn, it's not working!`;
    app.appendChild(errorMessage);
       }
         }

    request.send();

【问题讨论】:

  • 错误是Not a valid argument for 'page',API使用是否正确?
  • themuse.com/developers/api/v2 在该端点的文档上说页码是必需的,您必须发送该页码以获得有效响应。

标签: javascript api http-status-code-400


【解决方案1】:

如果您尝试在浏览器中加载 https://www.themuse.com/api/public/jobs,则会出现 400 错误以及以下错误消息:

{"code": 400, "error": "Not a valid argument for 'page'"}

该页面要求您通过您的GET 请求为其提供一个名为page 的非空变量。

如果您将页面加载为https://www.themuse.com/api/public/jobs?page=1(例如),您可以成功加载数据,您的问题就会消失!

【讨论】:

  • 添加 /jobs?/page=1 清除了错误!非常感谢。现在,进入下一条错误消息。 :)
猜你喜欢
  • 2016-08-31
  • 2016-07-25
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多