简体   繁体   English

使用 fetch 从 js 中的 http 中获取数据

[英]Fetch data from http in js using fetch

  • I am writing a basic JS function in Microsoft 365 Excel add-in generated using yeoman generator which I just want to fetch some data from a url , while fetching from https it is working fine. I am writing a basic JS function in Microsoft 365 Excel add-in generated using yeoman generator which I just want to fetch some data from a url , while fetching from https it is working fine.
  • But while doing the same with http I get an error saying TypeError: Failed to fetch .但是在对http执行相同操作时,我收到一条错误消息TypeError: Failed to fetch Now, I understand that I can't fetch from a http link but is there a way around.现在,我知道我无法从http链接中获取信息,但有办法解决。
  • Have included <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"> in the html file.html文件中包含<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
  • Code代码
// Fetch json value
      console.log(`Fetching`);
      var url = "http://1<ip>:<port>/fetch_api";
      //var url = "https://api.publicapis.org/entries";
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          accept: 'application/json',
        },
      });

      if (!response.ok) {
        throw new Error(`Error! status: ${response.status}`);
      }

      const result = await response.json();
      console.log(result);

Firstly you made mistype in headers dictionary headers: { 'Content-Type': 'application/json' } Then rememeber that this function have to be asynch.首先,您在标题字典headers: { 'Content-Type': 'application/json' }然后记住这个 function 必须是异步的。

no need to write that much code to get requests using fetch.无需编写那么多代码来使用 fetch 获取请求。 get request is the default method.获取请求是默认方法。 you can write just fetch(URL).你可以只写 fetch(URL)。 for another type of requests you should write method, headers, body, etc.对于另一种类型的请求,您应该编写方法、标头、正文等。

just write this function and invoke it.只需编写此 function 并调用它。

async function getData () {
const URL = 'your_url'
let response = await fetch(URL)
let data = await response.json()
console.log(data)
}

I am using an async await for fetching data.我正在使用异步等待来获取数据。 for any type of promise request you should use async await, this will help you to handle promises.对于任何类型的 promise 请求,您应该使用异步等待,这将帮助您处理承诺。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM