0

I'm unable to get either a success or failure from a simple axios call inside an Azure Function. Actually I can't get APIs to work in Azure full stop, but these are the simplest repo steps.

Code as follows:

const axios = require('axios');

module.exports = function (context, req) {

    context.res = {
        status: 200,
        body: callAPI(),
        headers: {
            "Content-Type": "application/json"
        }
    };
    context.done();

    // Controlled logging
    function Logger(msg) {
        context.log(msg);
    }


    function callAPI() {

        let res = { "state": "init" };
        
        const config = {
            method: 'get',
            url: 'https://catfact.ninja/fact',
            headers: {
                'Cookie': 'XSRF-TOKEN=eyJpdiI6IjBwRFJSemp0ZTE3dEpRVWEzQm1jRnc9PSIsInZhbHVlIjoic1lMSDZ3cjlUdnRlQnJDQkQ4d2RhcWlPWFUvTjJjekdXSzVNSVBZUUlIQ3N5dVFLaE0ydHpESXhIeUNENlBSWFo1UTFJc1VML2dZakhvaTV0Q3B1V21iUmhYdndtck5uSFhZTVBJUEtuUnBocENmWkJCa2JQOWVYQjFBb1lCbnAiLCJtYWMiOiI5NThlMWE1ZWYyYjA4MmY2YTM0YjE1Njk1ZTgyMDA0YTQxNmIxMDkwN2I5Y2NlOGUzODljZDFlYTE3NzlkZTUwIiwidGFnIjoiIn0%3D; cat_facts_session=eyJpdiI6IktLMDZVVEdSMnN3UDJheDVwUERFc0E9PSIsInZhbHVlIjoib01nZUhMY21XQysyelQza3dxZVRLQ1cybW0zaXgzV0kweGg0eU5Wanpwdkt1QlY3bGZmTDhlU2JlMmJhNVB6VkttelhuLzQ4Q0lHR3BBOVRZTExNVXRDcys2QVliZVFYcUx2U01FSmRHc2tTaDA1NTdMa2V6dVNqcS9JeXN5cVAiLCJtYWMiOiIyYTVjYjM2ZDljZDdhZTgxM2Q3NDYzNWZkZjE3MDljNGNlNDJkOWRmMTlkYjMzMzc4OWFhNzk2ZDg1ODg4Y2QyIiwidGFnIjoiIn0%3D'
            }
        };

        axios(config)
            .then(function (response) {
                res = response.data;
                res.state = "OK"
                Logger(`API called ok, res = ${res}`);
            })
            .catch(function (error) {
                res.state = "FAL"
                Logger(`API failed, err = ${error}`);
            });

        return res;

    }


};

Response suggests the call never happened:

{
  "state": "init"
}
Janine Rawnsley
  • 1,240
  • 2
  • 10
  • 20
  • I guess, you need to wait for result of the `axios` call, which means, you should call `context.done()` within `then`/`catch` callbacks. Better use `async` function definition as mentioned by @HariKrishnaRajoli-MT. – sschmeck Apr 06 '22 at 16:31

0 Answers0