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

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


当前回答

现在使用异步js,我们可以使用fetch()方法以更简洁的方式做出承诺。所有现代浏览器都支持异步函数。

async函数funcName(url){ Const response = await fetch(url); Var data = await response.json(); }

其他回答

原型让它变得非常简单

new Ajax.Request( '/myurl', {
  method:  'get',
  parameters:  { 'param1': 'value1'},
  onSuccess:  function(response){
    alert(response.responseText);
  },
  onFailure:  function(){
    alert('ERROR');
  }
});

jQuery:

$.get(
    "somepage.php",
    {paramOne : 1, paramX : 'abc'},
    function(data) {
       alert('page content: ' + data);
    }
);

浏览器(和Dashcode)提供了一个XMLHttpRequest对象,可用于从JavaScript发出HTTP请求:

function httpGet(theUrl)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
    xmlHttp.send( null );
    return xmlHttp.responseText;
}

然而,不鼓励同步请求,并将生成如下警告:

注意:从Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27)开始,由于对用户体验的负面影响,主线程上的同步请求已被弃用。

您应该在事件处理程序中发出异步请求并处理响应。

function httpGetAsync(theUrl, callback)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", theUrl, true); // true for asynchronous 
    xmlHttp.send(null);
}

在纯javascript和返回一个承诺:

  httpRequest = (url, method = 'GET') => {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open(method, url);
      xhr.onload = () => {
        if (xhr.status === 200) { resolve(xhr.responseText); }
        else { reject(new Error(xhr.responseText)); }
      };
      xhr.send();
    });
  }

集功能,食谱容易和简单

我准备了一组函数,它们在某种程度上是相似的,但如果你知道如何利用它,就会展示新的功能以及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));