Axios in nodejs can't make request

Viewed 43

What am I doing wrong in this GET method?

I'm making a GET request from an external API in my API controller.

but when performing the request, I get this error in my terminal:

 node:internal/process/promises:279
            triggerUncaughtException(err, true /* fromPromise */);
            ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "AxiosError: Request failed with status code 404".] {   
  code: 'ERR_UNHANDLED_REJECTION'

That's the code:

    static async getCentroMontagemByLoc(req, res) {
    const { cep, raio } = req.query;

    const response = await axios
      //pdr?cep=89245000&raio=40000
      .get(`${apiCentroMontagem}/pdr?cep=${cep}&raio=${raio}`, {
        httpsAgent,
      }).catch(err => res.send(err))

    res.status(200).json(response.data);
  }

EDIT(return the same error):

try {
      await axios.get(`${apiCentroMontagem}/pdr?cep=${cep}&raio=${raio}`, {
        httpsAgent,
      }).then(response => response.data)
    } catch (err) {
      console.log(err);
    } 

This is the url I'm making the request:

http://localhost:8080/centro-de-montagem/position?cep=joinville&raio=4000

this is an error returned in the browser when trying to access this function:

[Fiddler] ReadResponse() failed: The server did not return a complete response for this request. Server returned 0 bytes.

however, when making the request in the source API without going through the controller, it returns the request data ( it's not a 404 status, after all there is content on this endpoint )

What am I doing wrong in this GET method?

1 Answers

You are doing the catch wrong. instead of this:

try {
      await axios.get(`${apiCentroMontagem}/pdr?cep=${cep}&raio=${raio}`, {
        httpsAgent,
      }).then(response => response.data)
    } catch (err) {
      console.log(err);
    } 

do this:

axios.get(`${apiCentroMontagem}/pdr?cep=${cep}&raio=${raio}`, {
    httpsAgent,
}).then(response => console.log(response.data))
    .catch(err => console.log(err))

source: https://github.com/axios/axios/blob/v1.x/README.md

example

Related