Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make axios not to throw an exception when HTTP 302 is encountered, but return the AxiosResponse with it?

Tags:

node.js

axios

I have an axios code that calls an endpoint which returns 302 and a Location: header. I am writing a test which should evaluate method response and confirm the correct (HTTP 302) response as well as check Location: URL contents.

So I have a test code (Jest)

   let axiosReply = await axios.get(this.redirectUrl, {
       maxRedirects: 0 // do not follow redirects...
   });
   expect(axiosReply.status).toBe(302);
   // some checks of header Location: follow

however, axios throws an error:

Error: Request failed with status code 302

    at createError (C:\<my project folder>\node_modules\axios\lib\core\createError.js:16:15)
    at settle (C:\<my project folder>\node_modules\axios\lib\core\settle.js:17:12)
    at IncomingMessage.handleStreamEnd (C:\<my project folder>\node_modules\axios\lib\adapters\http.js:260:11)
    at IncomingMessage.emit (events.js:215:7)
    at endReadableNT (_stream_readable.js:1184:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)

How can I configure Axios just to return the reply and do not throw an error?

like image 947
onkami Avatar asked Nov 18 '25 02:11

onkami


1 Answers

In order not to throw, use valudateStatus option:

 result = await axios.get(this.url, {
            validateStatus: function (status) {
                // if this function returns true, exception is not thrown, so
                // in simplest case just return true to handle status checks externally.
                return true;
            }
        });


if (result.status === StatusCodes.FORBIDDEN) {
   // react on a 403 error in a custom way
}
like image 72
onkami Avatar answered Nov 19 '25 20:11

onkami