简体   繁体   English

使用Java Script / AJAX中的基本身份验证将POST请求发送到REST API

[英]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. 我正在做一个副项目,在该项目中,我必须创建一个HTML页面并将POST请求发送到Heroku上托管的REST API。 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. 这里的问题是REST API中具有基本身份验证实现。

I'm from Java/backend background. 我来自Java /后端背景。 The Googleing, research, and trials didn't help much. Googleing,研究和试验并没有太大帮助。 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! 由于我是JS / AJAX的新手,因此不胜感激!

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 您可以使用jquery beforeSend添加授权标头

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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