Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/448.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取API以获取HTML响应_Javascript_Fetch Api - Fatal编程技术网

Javascript 获取API以获取HTML响应

Javascript 获取API以获取HTML响应,javascript,fetch-api,Javascript,Fetch Api,我正在尝试使用FetchAPI获取页面的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(resp

我正在尝试使用FetchAPI获取页面的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)
});
它返回空字符串。猜猜它为什么不起作用?

关于
'no-cors'
(来自MDN,emphasis mine)

防止方法不是HEAD、GET或POST。如果任何ServiceWorkers截获这些请求,则他们不得添加或覆盖任何头,除非。此外,JavaScript可能无法访问结果的任何属性。这可确保ServiceWorkers不会影响Web的语义,并防止跨域泄漏数据所引起的安全和隐私问题

因此,这将启用请求,但将做出响应,即,您将无法从中获得任何信息,除非知道目标在那里

因为您正试图获取一个跨源域,所以除了代理路由之外没有什么可做的


PS:这里有一个片段向您显示请求确实是不透明的:

var quizUrl='1〕http://www.lipsum.com/';
取回(quizUrl{
模式:“无cors”,
方法:“获取”
}).然后(功能(响应){
console.log(response.type)
}).catch(函数(err){
console.log(err)//这不会触发,因为没有实际的错误

});我想这可能会有所帮助,使用如下:

fetch('/url/to/server')
。然后(res=>{
返回res.text();
})
。然后(数据=>{
$('#container').html(数据);
});
在服务器端,以纯文本形式返回内容,而不设置标题内容类型

我使用
$('#container')
表示您想要的容器 检索html数据后要执行的html数据

获取json数据的区别在于使用
res.json()
代替
res.text()

此外,不要附加任何标题如果您有自己的后端,请尝试制作一个从API检索信息的函数(在后端),并使用前端从函数检索信息。出于安全原因,某些API不允许通过浏览器(前端)直接检索数据

总结:

==>从后端创建一个从API检索信息的函数


==>然后从前端创建一个函数,从后端返回的函数中检索数据回答:以防万一,您在这里寻找如何使用async/await或promises(与axios相比)发出GET和POST Fetch api请求

我使用jsonplaceholder fake API演示:

使用异步/等待获取api GET请求:

         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()
    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()
使用异步/等待获取api POST请求:

         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()
    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()
使用承诺获取请求:

  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)
  })
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)
  })  
使用承诺发布请求:

  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)
  })
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获取请求:

        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()
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()
使用Axios发布请求:

        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()
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()

在web控制台中查看时会看到什么?另外:
内容类型
请求头与响应类型无关。您不想在上面的请求中指定它,您没有向服务器发送HTML。打开chrome inspector,转到[Network]点击,然后重试。您将看到xhr日志。您可以从那里看到整个请求/响应主体。先检查一下身体是空的。@modernator,你可以自己试试。请求成功,但响应是
“不透明的”
,即不适用于js。此外,我不会重复说
内容类型
与此无关,但这是一个很好的观点!跨源读取阻止(CORB)使用MIME类型text/html阻止跨源响应。有关详细信息,请参阅。加载失败:从“”重定向到“”已被CORS策略阻止:请求的资源上不存在“Access Control Allow Origin”标头。因此,不允许访问源“”。如果不透明响应满足您的需要,请将请求的模式设置为“no cors”以获取禁用cors的资源。我遇到错误:跨源读取阻止(CORB)使用MIME类型text/html阻止跨源响应。有关更多详细信息,请参阅。这是一个服务器配置,似乎您试图从不允许跨源访问的服务器获取。任何人,请提供帮助-我的API正在返回HTML响应,我可以在HTML字符串响应(如jquery)中获取特定元素吗?如果有人有任何示例或包,请建议如果我理解正确,您希望使用选择器获取HTML元素,否则称为web抓取。使用与Node.js类似的库