Leo*_*sse 13 node.js typescript node-fetch
我开始在我的 nodejs 项目中使用 Typescript。为了访问一些外部 API,我使用 node-fetch 来发出请求。在设置 PUT 请求时,会弹出一个错误,说给定的主体不可分配给 type RequestInit
:
错误:
Error:(176, 28) TS2345:Argument of type '{ headers: Headers; method: string; body: MyClass; }' is not assignable to parameter of type 'RequestInit'.
Types of property 'body' are incompatible.
Type 'MyClass' is not assignable to type 'BodyInit'.
Type 'MyClass' is not assignable to type 'ReadableStream'.
Property 'readable' is missing in type 'MyClass'.
Run Code Online (Sandbox Code Playgroud)
我的课:
class MyClass {
configId: string;
adapterType: string;
address: string;
constructor(configId: string, adapterType: string, address: string) {
this.configId = configId;
this.adapterType = adapterType;
this.address = address;
}
// some methods
}
Run Code Online (Sandbox Code Playgroud)
调用:
let body = new MyClass("a", "b", "c")
let url = config.url + "/dialog/" + dialogId
let headers = new Headers()
// Append several headers
let params = {
headers: headers,
method: "PUT",
body: body
}
return new Promise((resolve, reject) => {
Fetch(url, params) // <-- error is shown for params variable
.then(res => {
// Do stuff
resolve(/*somevalue*/)
})
}
Run Code Online (Sandbox Code Playgroud)
我应该如何使主体对象兼容?
Rus*_*kin 16
你需要对你的身体进行字符串化:
let params: RequestInit = {
headers: headers,
method: "PUT",
body: JSON.stringify(body)
}
Run Code Online (Sandbox Code Playgroud)
hbo*_*boo 11
我可以想到两种可能的方法 - 一种是以特定方式设置标题以补充您的body
类型将解决它。
另一个想法是类的实例可能不是合适的主体类型。你能把它串起来吗?
更新:我在 RequestInit 也有一个奇怪的错误,它通过指定选项的类型(你称之为“params”)对象来解决,如下所示:
let params: RequestInit = {
...
}
Run Code Online (Sandbox Code Playgroud)
我必须RequestInit
从内置打字稿导入node-fetch
而不是使用内置打字稿。
IE
这:
import fetch, { RequestInit } from 'node-fetch'
let params: RequestInit = {
headers: headers,
method: "PUT",
body: JSON.stringify(body)
}
Run Code Online (Sandbox Code Playgroud)
不是这个:
import fetch from 'node-fetch'
let params: RequestInit = {
headers: headers,
method: "PUT",
body: JSON.stringify(body)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13012 次 |
最近记录: |