fetch API 返回一个空字符串

fetch API returning an empty string

我正在尝试使用 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)
});

它returns 空字符串。猜猜为什么它不起作用?

关于 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 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,也就是说,除了知道目标在那里之外,您将无法从中得到任何东西。

由于您正在尝试获取 cross-origin 域,因此除了代理路由之外别无他法。


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('/url/to/server')
.then(res => {
    return res.text();
})
.then(data => {
    $('#container').html(data);
});

并且在服务器端,return 内容为纯文本,无需设置 header content-type。

我用$('#container')表示你想要的容器 html 检索后的数据。

与获取 json 数据的区别在于使用 res.json() 代替 res.text() 而且,不要附加任何 headers

如果您有自己的后端,请尝试创建一个函数(在您的后端)从 API 检索信息并使用您的前端从您的函数检索信息。出于安全原因,某些 API 不允许直接通过浏览器(前端)检索数据。

总结:

==>从后端创建一个函数,从 API

检索信息

==>然后从前端创建一个函数,从后端返回的函数中检索数据

2021 答案:以防万一您在这里寻找如何使用 async/await 或 promises 进行 GET 和 POST 获取 api 请求,与 axios 相比。

我正在使用 jsonplaceholder fake API 来演示:

获取 api GET 请求使用 async/await:

         const asyncGetCall = async () => {
            try {
                const response = await fetch('https://jsonplaceholder.typicode.com/posts');
                 const data = await response.json();
                // enter you logic when the fetch is successful
                 console.log(data);
               } catch(error) {
            // enter your logic for when there is an error (ex. error toast)
                  console.log(error)
                 } 
            }


          asyncGetCall()

获取 api POST 请求使用 async/await:

    const asyncPostCall = async () => {
            try {
                const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
                 method: 'POST',
                 headers: {
                   'Content-Type': 'application/json'
                   },
                   body: JSON.stringify({
             // your expected POST request payload goes here
                     title: "My post title",
                     body: "My post content."
                    })
                 });
                 const data = await response.json();
              // enter you logic when the fetch is successful
                 console.log(data);
               } catch(error) {
             // enter your logic for when there is an error (ex. error toast)

                  console.log(error)
                 } 
            }

asyncPostCall()

使用 Promises 的 GET 请求:

  fetch('https://jsonplaceholder.typicode.com/posts')
  .then(res => res.json())
  .then(data => {
   // enter you logic when the fetch is successful
    console.log(data)
  })
  .catch(error => {
    // enter your logic for when there is an error (ex. error toast)
   console.log(error)
  })

POST 使用 Promises 的请求:

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
   body: JSON.stringify({
     // your expected POST request payload goes here
      title: "My post title",
      body: "My post content."
      })
})
  .then(res => res.json())
  .then(data => {
   // enter you logic when the fetch is successful
    console.log(data)
  })
  .catch(error => {
  // enter your logic for when there is an error (ex. error toast)
   console.log(error)
  })  

使用 Axios 的 GET 请求:

        const axiosGetCall = async () => {
            try {
              const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts')
    // enter you logic when the fetch is successful
              console.log(`data: `, data)
           
            } catch (error) {
    // enter your logic for when there is an error (ex. error toast)
              console.log(`error: `, error)
            }
          }
    
    axiosGetCall()

POST 使用 Axios 请求:

const axiosPostCall = async () => {
    try {
      const { data } = await axios.post('https://jsonplaceholder.typicode.com/posts',  {
      // your expected POST request payload goes here
      title: "My post title",
      body: "My post content."
      })
   // enter you logic when the fetch is successful
      console.log(`data: `, data)
   
    } catch (error) {
  // enter your logic for when there is an error (ex. error toast)
      console.log(`error: `, error)
    }
  }


axiosPostCall()