【问题标题】:empty response from rest api using javascript fetch method (got a Json response on Postman)使用 javascript fetch 方法从 rest api 得到空响应(在 Postman 上得到 Json 响应)
【发布时间】:2022-08-05 23:02:20
【问题描述】:

设法在 Postman 中获得 JSON 响应,但在控制台中得到一个空响应,没有任何错误。

这是代码:

function getFetch() {
  const url = `https://fantasy.premierleague.com/api/bootstrap-static/`;

  let requestOptions = {
    method: \"GET\",
    redirect: \"follow\",
    mode: \'no-cors\',
    \"Access-Control-Allow-Origin\": \"*\",
    \"Access-Control-Allow-Methods\": \"GET\",
    \"Access-Control-Allow-Headers\": \"x-requested-with\"
  };

  fetch(
    \"https://fantasy.premierleague.com/api/bootstrap-static/\",
    requestOptions
  )
    .then((response) => response.text())
    .then((result) => console.log(result))
    .catch((error) => console.log(\"error\", error));
}

P.S:如果我在浏览器中输入 URL,我也会得到 JSON。但不是用 fetch

标签: javascript rest fetch-api


【解决方案1】:

假设您在浏览器中尝试,客户端:

  1. 跨域mode: 'no-cors'请求有no access to response body和headers,基本上都是盲目发送数据但看不到结果。

  2. 那些Access-Control-… headers 不是针对请求的,而是针对服务器响应的。如果服务器用它们进行响应,则响应将从所有来源读取。 (前提是mode: no-cors 没有像上面描述的那样自我限制此类请求。)

    您可以看到,无论您获取什么,响应始终是 status: 0ok: false

    function runFetch() {
      console.clear();
      fetch(
          url.value, {
            mode: nocors.checked ? 'no-cors' : 'cors'
          },
        )
        .then((response) => {
          console.log('Response status:', response.status, ', OK:', response.ok);
          return response.text()
        })
        .then((result) => console.log("Result: »" + result + "«"))
        .catch((error) => console.log("error", error.message));
    }
    
    runFetch()
    <label>URL: <input id="url" value="https://fantasy.premierleague.com/api/bootstrap-static/" /></label>
    <br><label>no-cors: <input type="checkbox" id="nocors" checked /></label>
    <br><button onclick="runFetch()">run</button>

【讨论】:

    猜你喜欢
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    相关资源
    最近更新 更多