5

I am trying to perform an Axios request using the URL type. But I get the error 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)
  }
}

How am I suppose to make it work? I am half a mind to put it back into a string, but I feel like it's a regression.

3
  • Axios expects a string, as the error tells you - you could pass this.urlDevices.toString(), or have a facade for Axios that accepts a URL (which would have other benefits), but what was the objective in making it a URL to start with? Commented Oct 20, 2020 at 12:40
  • Well, I am manipulating a URL, therefore it made sense to use this type to be more rigourous. Ain't it the reason to use typescript instead of vanilla JS in the first place ? Commented Oct 20, 2020 at 12:43
  • 3
    You can use .toString() to stringify the url: await axios.post(this.urlDevices.toString(), body) Commented Oct 20, 2020 at 13:24

1 Answer 1

4

Like the error says, you're giving a URL where a string is expected.

If you want to keep using the type URL for some reasons, you can do the following: give this.urlDevices.toString() as the first parameter of the axios.post() method.

Or you can just type your urlDevices as a string if you're not planning on using URL's static methods.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.