我需要在JavaScript中做一个HTTP GET请求。最好的方法是什么?
我需要在Mac OS X的dashcode小部件中做到这一点。
我需要在JavaScript中做一个HTTP GET请求。最好的方法是什么?
我需要在Mac OS X的dashcode小部件中做到这一点。
当前回答
在纯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();
});
}
其他回答
在你的小部件的信息。plist文件,不要忘记设置你的AllowNetworkAccess键为true。
<button type="button" onclick="loadXMLDoc()"> GET CONTENT</button>
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
var url = "<Enter URL>";``
xmlhttp.onload = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == "200") {
document.getElementById("demo").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
你可以通过两种方式获得HTTP get请求:
该方法基于xml格式。您必须为请求传递URL。 xmlhttp.open(“获得”、“URL”,真正的); xmlhttp.send (); 它是基于jQuery的。您必须指定要调用的URL和function_name。 $ (btn) .click(函数(){ 美元。Ajax ({url: "demo_test.txt", success: function_name(result) { $ (" # innerdiv ") . html(结果); }}); });
// 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()
集功能,食谱容易和简单
我准备了一组函数,它们在某种程度上是相似的,但如果你知道如何利用它,就会展示新的功能以及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));