获取API以获取HTML响应 [英] fetch API to get HTML response

查看:142
本文介绍了获取API以获取HTML响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用fetch API获取页面的HTML。这是我的代码。

I am trying to get a page's HTML using fetch API. Here is my code.

var quizUrl = 'http://www.lipsum.com/';
var myHeaders = new Headers();
myHeaders.append('Content-Type', 'text/html');
fetch(quizUrl,{
    mode: 'no-cors',
    method: 'get',
    headers: myHeaders
}).then(function(response) {
    response.text().then(function(text) {
        console.log(text);
    })
}).catch(function(err) {
  console.log(err)
});

它返回空字符串。任何猜测为什么它不起作用?

It returns empty string. Any guesses why it doesn't work?

推荐答案

关于 Request.mode 'no- cors' (来自MDN,强调我的)


防止该方法被除了HEAD,GET或POST之外的任何东西。如果任何ServiceWorkers拦截这些请求,除了这些之外,他们可能不会添加或覆盖任何标题。 。此外, JavaScript可能无法访问生成的响应<的任何属性/ a>。这可确保ServiceWorkers不会影响Web的语义,并防止因跨域泄漏数据而导致的安全和隐私问题。

Prevents the method from being anything other than HEAD, GET or POST. If any ServiceWorkers intercept these requests, they may not add or override any headers except for these. In addition, JavaScript may not access any properties of the resulting Response. This ensures that ServiceWorkers do not affect the semantics of the Web and prevents security and privacy issues arising from leaking data across domains.

所以这将启用请求,但会将响应设为 opaque ,即除非知道目标在那里,否则您将无法从中获取任何信息。

So this will enable the request, but will make the Response as opaque, i.e, you won't be able to get anything from it, except knowing that the target is there.

因为你试图获取跨域域,所以没有什么比代理路由更多了。

Since you are trying to fetch a cross-origin domain, nothing much to do than a proxy routing.

PS:这是一个片段,显示请求确实是不透明的:

PS : here is a snippet showing you that the request is indeed opaque :

var quizUrl = 'http://www.lipsum.com/';
fetch(quizUrl, {
  mode: 'no-cors',
  method: 'get'
}).then(function(response) {
  console.log(response.type)
}).catch(function(err) {
  console.log(err) // this won't trigger because there is no actual error
});

这篇关于获取API以获取HTML响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆