简体   繁体   中英

Sending a POST request to a REST API with Basic Authentication in Java Script/AJAX

I'm working on a side project where I have to create an HTML page and send a POST request to a REST API hosted on Heroku. I'm getting the information needed from the user through text boxes. The problem here is the REST API has a Basic Authentication implementation in it.

I'm from Java/backend background. The Googleing, research, and trials didn't help much. There aren't any tutorials for the same too. My code is as follows. I'm not sure where to plug in the code for Basic Authentication. As I'm completely new to JS/ AJAX, any help would be greatly appreciated!

Thanks!

<script type="text/javascript">

        $(document).ready(function () {
               $('#createuserbutton').click(function () {
                var un = $('#username').val();
                var pw = $('#password').val();
                var fn = $('#firstName').val();
                var ln = $('#lastName').val();

                $.post("https://example.com/createUser", 
                {
                    firstName: fn,
                    lastName: ln,
                    authority: 'ROLE_USER',
                }, function(data, status){
                    $("#createuserpre").html(JSON.stringify(data, undefined, 2));
                    alert("data: " + data + " status: " + status)
                });
            });

        });
    </script>

You can use jquery beforeSend to add authorization header

<script type="text/javascript">

    $(document).ready(function () {
           $('#createuserbutton').click(function () {
            var un = $('#username').val();
            var pw = $('#password').val();
            var fn = $('#firstName').val();
            var ln = $('#lastName').val();

            $.post("https://example.com/createUser", 
            {
                firstName: fn,
                lastName: ln,
                authority: 'ROLE_USER',
            }, beforeSend: function (xhr) {
                 xhr.setRequestHeader('Authorization', 'Basic ' + btoa('user:password'));
            }, function(data, status){
                $("#createuserpre").html(JSON.stringify(data, undefined, 2));
                alert("data: " + data + " status: " + status)
            });
        });

    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM