【问题标题】:Request were sent successfully,but return an empty promise when use 'fetch'请求发送成功,但使用 'fetch' 时返回一个空承诺
【发布时间】:2017-03-10 00:14:37
【问题描述】:

我使用 React 并 fetch 发送如下请求:

fetch(`http://www.bilibili.com/index/catalogy/1-3day.json`,{
        mode: "no-cors"
    }).then(r => r.json()).then(r => {
        console.log(r);
    }).catch(err => {console.log(err);})

响应就在网络标签中

但它会抛出一个错误:

SyntaxError: Unexpected end of input
at SyntaxError (native)
at http://127.0.0.1:8888/js/video.bundle.js:30174:15

当我尝试记录承诺时,它似乎是一个奇怪的对象:

Response {type: "opaque", url: "", status: 0, ok: false, statusText: ""…}

this is the picture

有人可以帮忙吗?我真的很困惑

【问题讨论】:

  • 我想你会发现该网站不希望你使用它的资源......即这是一个 CORS 问题
  • 它是否以正确格式的 JSON 响应?尝试return res.text(); 而不是return res.json(); 来查明问题
  • @deadlock,OP 声明 the response is right in the network tab - 这是一个 CORS 问题
  • 我尝试在我的 PC 上运行另一个 api(本地 nodejs 服务器),这一次,json 数据和 promise 运行良好。这确实是一个 CORS 问题。
  • 但是如果有什么方法可以得到我想要的数据呢?也许改变标题origin

标签: javascript promise cors fetch-api


【解决方案1】:

您不能向不支持cross origin resource sharing (CORS) 的外部服务器发出请求。

通过在请求上设置no-cors 模式,您明确地告诉服务器在无法访问其内容的情况下发出副作用请求。这类似于您从第三方网站在 HTML 中放置 <img> 标记并且无法访问其内容 - 它对调用代码是不透明的。

您需要在服务器端下载该 json,然后从您自己的服务器提供它以避免该问题。

【讨论】:

  • 感谢您对此的回答,但现在我面临一个新问题.. 当我尝试使用 nodejs、python 或 java 程序并使用不同的编码方式请求数据时(utf8, gb2312...),它无法获得我想要的正确数据,就像浏览器中显示的那样,太神奇了。
  • nodejs: ``` var request = require("request"); var http = 要求(“http”); var url = "bilibili.com/index/catalogy/1-3day.json"; http.get(url,function(res){ var cc = "" res.setEncoding("utf-8"); res.on("data",function(c){ cc += c }) res.on( "结束",function(){ console.log(cc); }) }) ```
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-28
  • 1970-01-01
  • 1970-01-01
  • 2017-05-15
  • 1970-01-01
  • 2015-07-12
  • 2015-11-27
相关资源
最近更新 更多