编程语言
首页 > 编程语言> > javascript – 获取API以获取HTML响应

javascript – 获取API以获取HTML响应

作者:互联网

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

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)
});

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

解决方法:

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

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 07001. In addition, JavaScript may not access any properties of the resulting 07002. 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,即除非知道目标在那里,否则您将无法从中获取任何内容.

由于您尝试获取跨域域,因此与代理路由无关.

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

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
});

标签:fetch-api,javascript
来源: https://codeday.me/bug/20191001/1837660.html