Add property headers upon request before sending a form in html Js or AngularJs

0

I have the following form created with native JavaScript, I need to add a property to the headers so that the request is authorized.

    var form = document.createElement('form');
    form.id='formulario_auxiliar';
    form.action = 'url';
    form.method = 'GET';
    form.target = '_blank';
    form.style.display = 'none';


    var myHeaders = new Headers();

    myHeaders.append('Autorization', 'Bearer ' + localStorage.getItem("userToken"));



    form.headers= myHeaders; 
    
asked by Magzoa 06.01.2018 в 17:34
source

2 answers

0

To add headers to a request you must do it by ajax, my recommendation is that you use jQuery since it drastically decreases the lines of code to write.

First you have to add a listener of the form onSubmit and use the property .serialize() of jQuery More info

Then you have to create the request using the function .ajax() of jQuery.

.ajax Documentation ()

Examples of adding headers with .ajax ()

More information on the subject

    
answered by 08.01.2018 в 10:54
0

Thanks, I've searched a lot, and I just found the way to do with ajax but this time I'm using angular js. Below is an example of how I use it. Now the headers can be added by means of an interceptor created, since the request is made via ajax.

           $scope.openReport=function(url,type){

            $http({
                method : 'GET',
                url : 'http://localhost:8080/enterprisesoft/'+url,
                responseType: "blob"
            }).then(function successCallback(response) {
                console.log(response);
                 var blob = new Blob([response.data], {type: 'application/'+type});
                // FileSaver.saveAs(blob, getFileNameFromHttpResponse(response));

                 var fileURL = URL.createObjectURL(blob);
                 $window.open(fileURL);
            }, function errorCallback(response) { 

                console.log(response);
            });


        }
    
answered by 08.01.2018 в 21:27