【问题标题】:How to write http request in javascript?如何用javascript编写http请求?
【发布时间】:2015-11-10 21:27:35
【问题描述】:

我知道它可以完成,但我对 http 请求一点也不擅长。我有一个非常具体的我需要写。代码在这里,但我不知道将哪一行返回到我的应用程序以获取响应。

    var request = new XMLHttpRequest();

request.open('POST', 'https://v2.api.xapo.com/oauth2/token');

request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.setRequestHeader('Authorization', 'Basic YTVlMGExMTViYTc1MThjYzphNWUwYTExNWJhNzUxOGNjYTVlMGExMTViYTc1MThjYw==');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = "grant_type=client_credentials&redirect_uri=https://myURI.com";

request.send(body);

这就是我想要做的。

curl --include --request POST --header "Content-Type: application/x-www-form-urlencoded" --header "Authorization: Basic MYKEYHERE[auth]" --data-binary "grant_type=client_credentials&redirect_uri=MYREDIRECTURI" 'https://v2.api.xapo.com/oauth2/token'

这个API是here

【问题讨论】:

  • 我想你可以参考我的示例代码在下面stackoverflow.com/questions/33584038/…
  • 这并没有真正帮助我,因为我不明白。但它似乎确实是我需要的东西。你认为你可以看看你是否可以为我做一个例子,或者一个指南让我理解? @BNK
  • 恕我直言,developer.android.com/training/basics/network-ops/… 将有助于您开始学习
  • 我已经检查过了。如果您知道 http 协议已经做了什么,那就太好了,但我不知道。我现在正在学习它,但这是我完成我的应用程序的最后一部分代码,它对时间敏感。不过感谢您的参考。

标签: javascript apache http httprequest httpresponse


【解决方案1】:

请看以下代码:

  function loadDoc() {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
          document.getElementById("demo").innerHTML = xhttp.responseText;
        }
      };
      xhttp.open("POST", "demo_get2.asp?fname=Henry&lname=Ford", true);
      xhttp.send();
    }

首先您定义一个 XMLHttpRequest() 的实例,它将为您执行 http 请求

第二方法xhttp.onreadystatechange = function()将监听状态变化,这意味着一旦返回http响应就会执行

第三个 xhttp.open 方法将确定您的连接配置,例如在这里我们设置一个属性“POST”,然后确定您要发布的链接以及您要发布的变量,如下所示:

  1. 进入链接
  2. 放?标记
  3. 放变量名
  4. 放=
  5. 输入变量值
  6. 如果要发布更多变量,请放置并标记并重复步骤 3 4 5,否则不要放置任何内容。

第四方法xhttp.send()将启动对服务器的http请求,一旦获得响应,xhttp.onreadystatechange = function()将被调用,然后您可以通过xhttp.responseText获取响应的内容

我希望这个例子很清楚

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2018-09-28
    相关资源
    最近更新 更多