【发布时间】:2021-02-03 07:01:48
【问题描述】:
我正在尝试使用 URL 类型执行 Axios 请求。但我收到错误Argument type URL is not assignable to parameter type string
import { Injectable } from '@nestjs/common'
import { NotificationsInterface } from '../interface/notifications.interface'
import { OS, UserType } from '../../global.constants'
const axios = require('axios').default
@Injectable()
export class NotificationsGateway implements NotificationsInterface {
readonly urlDevices = new URL(
'https://blablablabla.amazonaws.com/Prod/devices'
)
async saveDeviceAuthenticationInfos(
userId: number,
userType: UserType,
deviceId: number,
pushToken: string,
operatingSystem: OS
): Promise<void> {
const body = {
userId,
userType,
deviceId,
pushToken,
operatingSystem,
}
await axios.post(this.urlDevices, body)
}
}
我想如何让它工作?我有点想把它放回字符串,但我觉得这是一种回归。
【问题讨论】:
-
Axios 需要一个字符串,正如错误告诉你的那样 - 你可以传递
this.urlDevices.toString(),或者为 Axios 提供一个接受URL的外观(这将有其他好处),但是什么是目标是让它成为URL开始? -
好吧,我正在处理一个 URL,因此使用这种类型更严格是有意义的。这不是首先使用 typescript 而不是 vanilla JS 的原因吗?
-
您可以使用
.toString()将url字符串化:await axios.post(this.urlDevices.toString(), body)
标签: typescript url types axios