Search code examples
javascriptajaxaxiosazure-functionsazure-http-trigger

Ajax call to Azure function returns no data


It is my first time using Azure Functions. I am trying to access a 3rd party API with an auth token passed in the header. I have had some success getting data back when I run the Azure function alone locally in that it logs the correct data to my console. I have deployed this basic function to Azure, and added * to the CORS list for testing. However, when I created a simple HTML file to host on our website with ajax within a script tag to get this data - so that I may eventually display it on the html page - nothing is returned. I have not found any other examples using my specific code base or with code this simple. There are no error messages, it just logs ''. Here is my html/JS script:

<script type="text/javascript">
$(document).ready(function () {
    console.log("fired off on ready...");
    var url = "https://{...}.azurewebsites.net/api/{...}?"
    
       $.ajax({
           method: "GET",
           url: url,
           crossDomain: true,
           success: function (respData) {
               console.log(respData);
                $("#functionData").html("<div style='padding: 5em 1em; text-align: center; color: #008800'>" + respData + "</div>");
           },
          error: function (jqXHR) {
              console.log(jqXHR)
              $("#functionData").html("<div style='padding: 1em; text-align: center; color: #660000'>Sorry, an error occurred: " + jqXHR.responseText + "</div>");
          }
       });
    })
</script>

And here is my index.js file in my Azure function:


module.exports = async function(context) {

var config = {
  method: 'get',
  url: 'http://{apiUrl}',
  headers: { 
    'auth-token': '{...}'
  }
};

await axios(config)
.then(function (response) {
  let res = JSON.stringify(response.data)
  context.log(res);
  return res;
})
.catch(function (error) {
  context.log(error);
});

}

And just in case it's relevant, here is my function.json file:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}

As I said, the context.log displays data in my terminal in VSCode when I run the azure function locally, so I had been operating under the assumption that it is also returning the data - but now I am not sure.

Any guidance you can offer would be much appreciated, I feel like I must be really close, but some configuration is just not quite right. Thanks in advance!


Solution

  • Regarding the issue, please refer to the following code

    My function app code

    const axios = require('axios');
    
    module.exports = async function (context, req) {
        context.log('JavaScript HTTP trigger function processed a request.');
    
        var config = {
            method: 'get',
            url: '',
            headers: { }
            };
        try{
           
            var response= await axios(config)
            const data=JSON.stringify(response.data)               
            context.res = {
                headers: {
                    'Content-Type': 'application/json'
                },
                body: data
            }
        }catch(err){
            context.log(err)
            throw err
        }
    
    
    }
    

    HTML

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>API</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
    $(document).ready(function () {
        $("#submit").click(function (e) {
           
           
                $.ajax({
                    type: "GET",
                    url: "",
                    dataType: "json",
                    success: function (respData, status, xhr) {
                        console.log(respData)
                       
                        #process data and show data
                    },
                    error: function (xhr, status, error) {
                        alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
                    }
                });
            
        });
      
        
    });
    </script>
    </head>
     
    <body>
    
      
    <button id="submit">Call API</button>
    <div id="message"></div>
    </body>
     
    </html>
    

    Test enter image description here