如何通过表单发布方法请求使用api键?

时间:2019-02-22 11:34:22

标签: jquery json

我尝试使用post方法通过表单获取json响应,但我仍然被禁止使用403。

window.onload = function() {
  document.getElementById("Save").onclick = function fun() {
    var x = document.forms["myForm"]["customerAccUserName"].value;
    var Url = "https://url.com/getAccountDetails?format=json&customerAccUserName=" + x;

    var xhr = new XMLHttpRequest();
    xhr.open('POST', Url, true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded", "Authorization', '123456'");
    xhr.send();
    xhr.onreadystatechange = processRequest;

    function processRequest(e) {
      if (xhr.readyState == 4 && xhr.status == 200) {
        //  alert(xhr.responseText);
        var response1 = JSON.parse(xhr.responseText);
        document.getElementById("AccNo").innerHTML = response1.name + ", " + response1.statusCode;
        document.getElementById("AccNo").innerHTML = response1.AccNo;
        document.getElementById("AccNo").innerHTML = response1.AccNo;
      }
    }
  }
}

我对此感到困惑,如何将api键放在标头上正确的方法

感谢您的帮助:(

1 个答案:

答案 0 :(得分:-1)

我认为您可以使用访存:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

例如:

fetch(`https://url.com/getAccountDetails?format=json&customerAccUserName=${x}`, {
  method: 'POST',
  headers: {
     'api-key-name': 'apikey',
     'Content-Type': 'application/x-www-form-urlencoded'
  }
})
.then(response => console.log(response));