How Set Authorization headers at HTML Form or at A href

后端 未结 1 1416
北恋
北恋 2021-01-12 11:54

I have this code:

            $.ajax({
                url: \"http://localhost:15797/api/values\",
                type: \'get\',
                contentType         


        
相关标签:
1条回答
  • 2021-01-12 12:36

    You need to send the Authorization argument in the HTTP request header, it's imposed by OAuth flows. Of course you can change it by making changes in OAuth server's code but if you've got no control on the OAuth server's code it's not possible.

    So answering your question, no you can't send them with the form's posted data. However, obviously you can put them in the hidden field and write a JS code to read it from the field and put it in the request header.

    e.g.

    HTML:

    <input id="tokenField" type="hidden" />
    <input id="submitButton" type="button" />
    

    Javascript:

    $('#submitButton').on('click',function(){
        $.ajax({
              url: "http://localhost:15797/api/values",
              type: 'GET',
              contentType: 'application/json',
              headers: {
                        "Authorization": "Bearer " + $('#tokenField').val()
                     },
              async: false
                }});
    

    Notice the async: false makes your call synchronous, just like a submit. And if you need to post other data to the server you can change the type: 'GET' to type: 'POST' and add another field named data and pass your form data through its value :

    <input id="firstName" type="text" />
    <input id="lastName" type="text" />
    <input id="tokenField" type="hidden" />
    <input id="submitButton" type="button" />
    
    $('#submitButton').on('click',function(){
        $.ajax({
              url: "http://localhost:15797/api/values",
              type: 'POST',
              data: { 
                      firstName: $('#firstName').val(),
                      lastName: $('#lastName').val()
                    },
              contentType: 'application/json',
              headers: {
                        "Authorization": "Bearer " + $('#tokenField').val()
                     },
              async: false
                }});
    
    0 讨论(0)
提交回复
热议问题