typescript无法使用react-native将标头添加到获取api

P.L*_*and 11 json typescript react-native fetch-api

我正在使用来自react-native的Fetch API,并且正在使用打字稿。我的代码如下所示:

let responseLogin = await fetch('http://url_example', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: requestBody
    });
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误,标题是:

 Argument of type '{ method: string; headers: { 'Content-Type': string; }; body: string; }' is not assignable to parameter of type 'RequestInit'.
  Types of property 'headers' are incompatible.
    Type '{ 'Content-Type': string; }' is not assignable to type 'Headers | string[][]'.
      Object literal may only specify known properties, and ''Content-Type'' does not exist in type 'Headers | string[][]'.
Run Code Online (Sandbox Code Playgroud)

我也尝试创建一个自定义标头,但没有任何运气:

    let requestHeaders = new Headers();
        requestHeaders.set('Content-Type', 'application/json');
        // I have also tried adding this at the end but no luck 
        // requestHeaders.get('Content-Type');
Run Code Online (Sandbox Code Playgroud)

我该如何添加标题?因为我找不到任何方法来实现这一目标,所以我不知道问题出在哪里。如果我在邮递员中测试这些,我会得到200的响应,在这里我会得到401的响应。我也尝试过使用该库来添加自定义标头:https : //www.npmjs.com/package/fetch-headers

我使用:Visual Studio代码1.81.1“本机”:“ 0.50.0”,“打字稿”:“ 2.6.1”

Pet*_*wen 6

您可以尝试输入为HeadersInit吗?

const requestHeaders: HeadersInit = new Headers();
requestHeaders.set('Content-Type', 'application/json');

const responseLogin = await fetch('URL', {
  method: 'POST',
  headers: requestHeaders,
  body: requestBody
});
Run Code Online (Sandbox Code Playgroud)

如果没有,您是否可以显示在问题中显示的Headers()构造函数启动该错误时遇到的错误?

  • 好吧,那就不是问题了。但你不需要给出类型,所以你也只能这样做 ```const requestHeaders = new Headers();``` (2认同)

小智 6

Headers我通过这样导入解决了这个问题:

import fetch, { Headers } from 'node-fetch';
Run Code Online (Sandbox Code Playgroud)


A. *_*ale 5

您的构建中包括哪些TypeScript库?您似乎对该headers属性的定义是错误的。在TypeScript 2.6.2中,headers属性的类型为HeadersInit,定义为: type HeadersInit = Headers | string[][] | { [key: string]: string };