简体   繁体   English

如何从 Typescript 中的 fetch 调用迭代/访问响应标头?

[英]How do I iterate/access response headers from a fetch call in Typescript?

Consider the following TS example:考虑以下 TS 示例:

fetch("http://localhost:3000/auth", {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
    body: JSON.stringify(data)
  })
  .then((response) => {
    // would like to store some information from the response's headers
    // like access tokens etc.

    // Typescript complains about this iteration (see more info below)
    for (var pair of response.headers.entries()) {
      console.log(pair[0] + ': ' + pair[1])
    }

    return response.json()
  })
  // get the response data etc...
  .then((data) => {
    console.log(data);
  })
  // log an error etc...
  .catch((error) => {
    console.log('ERROR: ', error);
  })

Normally, this would be valid but Typescript complains about the iteration and suggests a compiler option:通常,这将是有效的,但 Typescript 会抱怨迭代并建议使用编译器选项:

Type 'IterableIterator<[string, string]>' is not an array type or a string type.
Use compiler option '--downlevelIteration' to allow iterating of iterators.

Are there any downsides to using --downlevelIteration ?使用--downlevelIteration有什么缺点吗? Is there another way of accomplishing this without having to change the compiler options?是否有另一种无需更改编译器选项即可完成此操作的方法?

Thanks!谢谢!

Iterators (in some languages called Enumerators) were added in ES6. ES6 中添加了迭代器(在某些语言中称为枚举器)。 They are not present in ES5 and older.它们在 ES5 及更早版本中不存在。 Before ES6 only iterable construct was Array or so-called array like native objects.在 ES6 之前,只有可迭代构造是Array或所谓的数组,如本机对象。 ES6 brought iterators and features like for ... of that works with them. ES6 带来了迭代器和诸如for ... offor ... of特性。 When targeting below ES6 you have to use downlevelIteration in order to transpile ES6 iterator code to ES5 compatible code (iterator will be changed do Array s and for ... of will be replaced by ES5 valid syntax).当下面ES6目标,你必须使用downlevelIteration以transpile ES6迭代器代码ES5兼容的代码(迭代器将改为做Array S和for ... of将ES5有效的语法来代替)。 If you are using no other transpiler beside TSC you have no other choice but enable this flag.如果您除了 TSC 之外没有使用其他转译器,您别无选择,只能启用此标志。

const getHeaders = (headers: Headers) => {
  let headerObj: IObject = {};
  const keys = headers.keys();
    let header = keys.next();
    while (header.value) {
      headerObj[header.value] = headers.get(header.value);
      header = keys.next();
    }
  return headerObj;
};

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

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