我需要在JavaScript中做一个HTTP GET请求。最好的方法是什么?

我需要在Mac OS X的dashcode小部件中做到这一点。


当前回答

// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()

// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'restUrl', true)

request.onload = function () {
  // Begin accessing JSON data here
}

// Send request
request.send()

其他回答

没有回调的版本

var i = document.createElement("img");
i.src = "/your/GET/url?params=here";

下面是直接用JavaScript实现的代码。但是,如前所述,使用JavaScript库会更好。我最喜欢jQuery。

在下面的例子中,调用一个ASPX页面(作为穷人的REST服务)来返回一个JavaScript JSON对象。

var xmlHttp = null;

function GetCustomerInfo()
{
    var CustomerNumber = document.getElementById( "TextBoxCustomerNumber" ).value;
    var Url = "GetCustomerInfoAsJson.aspx?number=" + CustomerNumber;

    xmlHttp = new XMLHttpRequest(); 
    xmlHttp.onreadystatechange = ProcessRequest;
    xmlHttp.open( "GET", Url, true );
    xmlHttp.send( null );
}

function ProcessRequest() 
{
    if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) 
    {
        if ( xmlHttp.responseText == "Not found" ) 
        {
            document.getElementById( "TextBoxCustomerName"    ).value = "Not found";
            document.getElementById( "TextBoxCustomerAddress" ).value = "";
        }
        else
        {
            var info = eval ( "(" + xmlHttp.responseText + ")" );

            // No parsing necessary with JSON!        
            document.getElementById( "TextBoxCustomerName"    ).value = info.jsonData[ 0 ].cmname;
            document.getElementById( "TextBoxCustomerAddress" ).value = info.jsonData[ 0 ].cmaddr1;
        }                    
    }
}

短的、干净的:

const http = new XMLHttpRequest() http。打开(“得到”,“https://api.lyrics.ovh/v1/toto/africa”) http.send () http。onload = () => console.log(http.response)

上面有很多很好的建议,但不是很可重用,而且经常充满了DOM废话和其他隐藏了简单代码的无用之处。

下面是我们创建的一个可重用且易于使用的Javascript类。目前它只有一个GET方法,但这对我们来说是可行的。添加POST不应该对任何人的技能征税。

var HttpClient = function() {
    this.get = function(aUrl, aCallback) {
        var anHttpRequest = new XMLHttpRequest();
        anHttpRequest.onreadystatechange = function() { 
            if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
                aCallback(anHttpRequest.responseText);
        }

        anHttpRequest.open( "GET", aUrl, true );            
        anHttpRequest.send( null );
    }
}

使用它就像:

var client = new HttpClient();
client.get('http://some/thing?with=arguments', function(response) {
    // do something with response
});

集功能,食谱容易和简单

我准备了一组函数,它们在某种程度上是相似的,但如果你知道如何利用它,就会展示新的功能以及Javascript已经达到的简单性。


让一些基本常数


let data;
const URLAPI = "https://gorest.co.in/public/v1/users";
function setData(dt) {
    data = dt;
}

最简单的


// MOST SIMPLE ONE 
function makeRequest1() {       
    fetch(URLAPI)
        .then(response => response.json()).then( json => setData(json))
        .catch(error => console.error(error))
        .finally(() => {
            console.log("Data received 1 --> ", data);
            data = null;
    });
}

使用承诺和异步工具的变化


// ASYNC FUNCTIONS 
function makeRequest2() { 
    fetch(URLAPI)
        .then(async response => await response.json()).then(async json => await setData(json))
        .catch(error => console.error(error))
        .finally(() => {
            console.log("Data received 2 --> ", data);
            data = null;            
        });
}

function makeRequest3() {    
    fetch(URLAPI)
        .then(async response => await response.json()).then(json => setData(json))
        .catch(error => console.error(error))
        .finally(() => {
            console.log("Data received 3 --> ", data);
            data = null;
        });
}

// Better Promise usages
function makeRequest4() {
    const response = Promise.resolve(fetch(URLAPI).then(response => response.json())).then(json => setData(json) ).finally(()=> {
        console.log("Data received 4 --> ", data);

    })
}

一个线性函数的演示!!


// ONE LINER STRIKE ASYNC WRAPPER FUNCTION 
async function makeRequest5() {
    console.log("Data received 5 -->", await Promise.resolve(fetch(URLAPI).then(response => response.json().then(json => json ))) );
}

值得一提的是——> @Daniel De León可能是最干净的函数*

(async () =>
    console.log(
            (await (await fetch( URLAPI )).json())
            )
)();

上面的答案-> By @tggagne显示了HttpClient API的功能。

使用Fetch也可以实现同样的效果。根据此使用MDN获取展示了如何将INIT作为第二个参数传递,基本上打开了使用经典方法(get, post…)轻松配置API的可能性。


// Example POST method implementation:
async function postData(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

postData('https://example.com/answer', { answer: 42 })
  .then(data => {
    console.log(data); // JSON data parsed by `data.json()` call
  });

Node

在节点(服务器端)上无法获取

最简单的解决方案(2021年底)是使用Axios。

$ npm install axios

然后运行:

const axios = require('axios');
const request = async (url) => await (await axios.get( url ));
let response = request(URL).then(resp => console.log(resp.data));