Home > Software engineering >  How to use special symbols(like " ´ ", or " ~ ") in axios http requests
How to use special symbols(like " ´ ", or " ~ ") in axios http requests

Time:08-07

I'm developing a simple backend service in Nest JS to consume an api and retrieve data about some cities. I've been having problems to get axios http requests working when the parameter I use has some special characters like '~' or '^' in the name.

I've debbuged it and the url I feed the request is correct and it works in Postman for instance, but in the get request it only returns 'undefined'.

How can I make axios correctly work with those special symbols?

It's a brazilian portuguese system so there is the need to use those characters in the name of cities like São Paulo or Brasília because the API I consume will only identify the cities if I use the correct name.

I'm using nest js implementation of axios and making get requests through it as follows, the httpService implements the axios imported library:

 async callAneel(numOfItems,offset,sigUF,city) {
    const aneelData = [];
    let url = `https://dadosabertos.aneel.gov.br/api/3/action/datastore_search?resource_id=b1bd71e7-d0ad-4214-9053-cbd58e9564a7&limit=${numOfItems}&offset=${offset}&q={"SigUF":"${sigUF}","NomMunicipio":"${city}"}`

    try {
      var aneelAnswer = await lastValueFrom(this.httpService.get(url));
    }
    catch(error)
    {
      return;
    }
    
    for(let i = 0; i<aneelAnswer.data.result.records.length; i  ) {
      aneelData.push(aneelAnswer.data.result.records[i]);
    }

    return aneelData;
  }

CodePudding user response:

You don't need to pass the final URL. Instead, use the second arg of HttpService#get like this:

const url = `https://dadosabertos.aneel.gov.br/api/3/action/datastore_search`

this.httpService.get(url, {
  params: {
    limit: numOfItems,
    offset,
    // and so on
  }
})

Read their docs: https://axios-http.com/docs/req_config


btw if you won't use Observables at all, you could use this another lib instead: nestjs-http-promise

  • Related