【问题标题】:Fetch -API returning HTML instead of JSONFetch -API 返回 HTML 而不是 JSON
【发布时间】:2017-03-28 22:00:38
【问题描述】:

我有一个在 Postman 上测试过的 Spring REST API,它返回完全有效的 JSON。 但是,当我在前端 React 代码上调用相同的 API 时,它会返回 HTML。 这是我用来调用API的函数,

export function run(engine, mediaId, owner, target, access){
  let url = engine + "/" + mediaId + "?id=" + owner + "&targetId=" + target + "&access=" + access;

  return fetch(full_url, { credentials: "include",
                           headers: {
                             "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
                          }})
    .then((response) => {

      return response.json();})
    .then((data) => {
        console.log(data);

    })
    .catch((error) => {
        console.log(error);
    });
}

我在调用Unexpected token < Thus when I check using response.text() 时遇到语法错误,我可以看到返回的数据是 HTML 而不是 JSON。我需要在我的前端代码中更改哪些 API 才能返回 JSON。

【问题讨论】:

  • 请尝试“Content-Type”:“text/plain”
  • 你得到答案了吗?

标签: javascript json fetch-api


【解决方案1】:

标题不正确。 JSON 响应的有效标头:

headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  }

【讨论】:

  • 没有仍然返回 html
  • 对不起。你后来修改了你的问题,所以我错过了“意外令牌”这个词。
  • 接受:application/json 是关键
【解决方案2】:

如果您没有登录,有时 API 会返回 html 而不是 json,请同时确认

【讨论】:

  • 如果发生这种情况,我们该怎么办?
  • 这正是我的情况
【解决方案3】:

还要仔细检查您在postman 输入栏旁边的下拉框中选择了正确的HTTP 方法。

【讨论】:

    猜你喜欢
    • 2021-10-19
    • 2019-03-31
    • 2020-08-12
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    • 2022-01-01
    • 1970-01-01
    相关资源
    最近更新 更多