繁体   English   中英

使用 javascript fetch 方法从 rest api 得到空响应(在 Postman 上得到 Json 响应)

[英]empty response from rest api using javascript fetch method (got a Json response on Postman)

设法在 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));
}

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

  1. 跨域mode: 'no-cors'请求 无法访问响应体和响应头,基本上是盲目发送数据但看不到结果。

  2. 那些Access-Control-…标头不是针对请求的,而是针对服务器响应的。 如果服务器用它们进行响应,则响应将从所有来源读取。 (前提是此类请求不受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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM