-2

I am trying to figure out how to take data from an API that is secured with an authentication user and password. I ended up with the following code, but I am getting an error message preventing me from achieving my goal

The code for the HTML:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="js/jquery-3.5.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var content = $('#content');

            $('#btn').click(function () {
                var username = $('#txtUsername').val();
                var password = $('#txtPassword').val();

                $.ajax({
                    type: 'GET',
                    url: '(the api url)',
                    dataType: 'jsonp',
                    headers: {
                        'Authorization': 'Basic ' + btoa(username + ':' + password)
                    },
                    
                    success: function (data) {
                        
                        $.each(data, function (index, val) {
                            var cdrVal = val.cdr_root[0].cdr;
                            content.append('<li>' + cdrVal + '</li>')
                        });
                    },
                    complete: function (jqXHR) {
                        if (jqXHR.status == '401') {
                            content.empty();
                            content.append('<li style="color:red">'
                                + jqXHR.status + ' : ' + jqXHR.statusText + '</li>')
                        }
                    }
                });
            });

            $('#btnClear').click(function () {
                $("content").empty();
            });
        });
    </script>
</head>
<body>
    Username : <input type="text" id="txtUsername" />
    Password : <input type="password" id="txtPassword" />
    <br /><br />
    <input id="btn" type="button" value="Authenticate" />
    <input id="btnClear" type="button" value="Clear" />
    <ul id="content"></ul>
</body>
</html>

The error message:

jquery-3.5.1.min.js:2 GET (URL)&callback=jQuery3510613249910788189_1594517328830&_=1594517328834 net::ERR_ABORTED 400 (Bad Request)

What could be causing this? I have tried multiple things online but nothing has worked. I doubt it is the url itself as I can still access that via web browser.

migte
  • 1
  • 2

1 Answers1

0

beforeSend may be the way to go. From jQuery's documentation on $.ajax():

Use this to set custom headers, etc.

This question may be a duplicate of this one, though : Use basic authentication with jQuery and Ajax

berdosi
  • 61
  • 5
  • This did not work. I still get the error message, and I have switched out my auth to the before send function + the setRequestHeader. – migte Jul 12 '20 at 02:05