【问题标题】:How to send headers from HTML / UI in an API request to server?如何在 API 请求中将标头从 HTML / UI 发送到服务器?
【发布时间】:2018-08-26 18:56:05
【问题描述】:

我想在来自客户端的每个请求上添加 HTTP 标头。无法弄清楚如何。

曾尝试将以下脚本添加到 HTML 以设置标题,例如:

<script>
    res.setHeader('Authorization', "I am JWT Bearer token");
</script>

【问题讨论】:

  • 能否添加javascript请求的代码。像 $.ajax({ url: '....' })
  • 我只使用我写的很可能我错过了 smoething

标签: javascript node.js ajax api http


【解决方案1】:

您只能在从客户端的 AJax 或其他 API 请求模块进行 API 调用时添加标头,而不是通过提交 &lt;form&gt; 并向您的 &lt;form&gt; 添加操作

通过 Ajax 调用,您可以执行以下操作:

<script>
 function submitForm() {
    var data = {};//Your JSON Data

    //You can make this a global variable to use everywhere.
    //Or you can make a function what will be responsible to make all aJax calls.
   //Function will receive 3 arguments: json data, success-callback and error-callback, or in place of call back you can use Promise. 
    var headers = {
        "Contect-Type": "application/json",
        "Authorization": "Basic : your auth"
    };
    $.ajax({
        url: 'http://google.com',
        type: 'POST',//'GET','PUT','DELETE'
        headers: headers,
        data: data,
        success: function(result) {
            alert("success");
        },
        error: function (error) {
            alert('error ',error);
        }
    });
  }
</script>

你需要调用这个函数来代替使用

&lt;form action="submitAPI" method="POST"&gt;&lt;input type="submit" value="Submit" /&gt;&lt;/form&gt;

使用这个:

&lt;form&gt;&lt;input onclick="submitForm()" value="Submit" /&gt;&lt;/form&gt;

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 2013-10-24
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多