How Set Authorization headers at HTML Form or at A href

半腔热情 提交于 2019-12-19 07:58:21

问题


I have this code:

            $.ajax({
                url: "http://localhost:15797/api/values",
                type: 'get',
                contentType: 'application/json',
                headers: {
                    "Authorization": "Bearer " + token
                }
            })

works fine, but I want to do that without using Ajax, I want something like that:

        <form action="http://localhost:15797/api/values" method="get">
            <input type="hidden" name="headers[Authorization]" value="Bearer token" />
            <input type="submit" />
        </form>

Is it possible? Or just do something like that without XMLHttpRequest? How?


回答1:


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
            }});


来源:https://stackoverflow.com/questions/38422520/how-set-authorization-headers-at-html-form-or-at-a-href

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!