如何用javascript编写http请求?
我知道这是可以做到的,但我对http请求一点也不在行。我有一个非常具体的我需要写。代码在这里,但我不知道哪一行返回到我的应用程序的响应如何用javascript编写http请求?,javascript,apache,http,httprequest,httpresponse,Javascript,Apache,Http,Httprequest,Httpresponse,我知道这是可以做到的,但我对http请求一点也不在行。我有一个非常具体的我需要写。代码在这里,但我不知道哪一行返回到我的应用程序的响应 var request = new XMLHttpRequest(); request.open('POST', 'https://v2.api.xapo.com/oauth2/token'); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
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为请参阅以下代码:
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请求
second方法xhtp.onreadystatechange=function()
将侦听状态更改,这意味着在返回http响应后将执行状态更改
thirdxhttp.open
方法将确定您的连接配置,例如,这里我们设置了一个属性“POST”,然后确定您要发布的链接以及您要发布的变量,如下所示:
xhttp.send()
将启动对服务器的http请求,一旦获得响应,将调用xhttp.onreadystatechange=function()
,然后您可以使用xhttp.responseText
获取响应内容
我希望这个例子很清楚我想你可以参考我下面的示例代码,这对我没有帮助,因为我不理解它。但这似乎确实是我所需要的。你认为你能看到你是否能为我树立一个榜样,或是一个我能理解的指南吗@B Kimho,开始学习对你有好处我查过了。如果你知道http协议已经做了什么,这很好,但是我不知道。我现在正在学习它,但这是一点点代码,是我完成我的应用程序的最后一块,这是时间敏感的。谢谢你的推荐。