我正在使用react native的Fetch API和typescript.

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

但我得到了如下错误,其中标题是:

 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[][]'.

我还try 创建自定义标题,但没有成功:

    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');

我怎样才能给它添加标题?因为我找不到任何方法来实现这一点,我不知道问题出在哪里.如果我在《postman 》中测试这些,我会得到200条回复,这里我会得到401条回复.

我使用:

推荐答案

你能试着把它打成HeadersInit吗?

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

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

如果没有,你能展示一下当你用Headers()构造函数初始化它时,你会遇到什么错误吗?你在问题中展示过?

Typescript相关问答推荐

PrimeNG Inputnumber,具有自定义号码格式器

Typescript:假设foo不在类型栏中,而它在:如何调试

如何将http上下文附加到angular中翻译模块发送的请求

如何使打包和拆包功能通用?

需要使用相同组件重新加载路由变更数据—React TSX

TypeScript类型不匹配:在返回类型中处理已经声明的Promise Wrapper

使某些类型的字段变为可选字段'

Angular 错误NG0303在Angular 项目中使用app.Component.html中的NGFor

仅针对某些状态代码重试HTTP请求

TypeScrip:逐个 case Select 退出noUncheck kedIndexedAccess

TypeScrip界面属性依赖于以前的属性-针对多种可能情况的简明解决方案

如何将泛型对象作为返回类型添加到类型脚本中

函数重载中的不正确TS建议

寻址对象中路径的泛型类型

如何编写在返回函数上分配了属性的类型安全泛型闭包

使用Type脚本更新对象属性

如何使用泛型函数参数定义类型脚本函数

具有匹配功能的TS通用事件处理程序

打字脚本错误:`不扩展[Type]`,而不是直接使用`[Type]`

仅当定义了值时才按值筛选数组