ZetCode

JavaScript fetch

最后修改于 2023 年 10 月 18 日

在本文中,我们将展示如何使用 fetch API 在 JavaScript 中异步获取资源。

fetch 函数

fetch 是一个全局函数,它接受 url 和 options 参数,并返回一个 promise。该 promise 解决为请求的响应。

let promise = fetch(url, [options])

如果我们不提供 options,则会生成一个简单的 GET 请求,下载 URL 的内容。

当我们获取响应时,我们可以检查 HTTP 状态或标头,但我们还没有正文。要获取响应的正文,我们调用以下方法之一

fetch 函数可以与回调函数以及 async/await 关键字一起使用。

JavaScript fetch 简单示例

在第一个示例中,我们使用 fetch 函数生成一个简单的异步 GET 请求。

<script>
    fetch('http://time.jsontest.com')
        .then(res => res.json())
        .then((data) => {

            console.log(data);
        }).catch(err => console.error(err));
</script>

在这个例子中,我们使用回调。time.jsontest.com 以 JSON 格式返回当前时间。从响应对象中,我们使用 json 函数检索数据。

Object { date: "01-26-2021", milliseconds_since_epoch: 1611661589016, 
    time: "11:46:29 AM" }

我们在浏览器中检查控制台输出。

<script>

    async function doRequest() {
        let url = 'http://time.jsontest.com';
        let res = await fetch(url);

        if (res.ok) {

            let json = await res.json();

            return json;
        } else {
            return `HTTP error: ${res.status}`;
        }
    }

    doRequest().then(data => {
        console.log(data);
    });

</script>

在这个例子中,我们使用 async/await 关键字。

if (res.ok) {

ok 属性对于 HTTP 状态码 200-299 返回布尔值 true。

JS fetch GET 请求

以下示例创建一个简单的 GET 请求并将结果作为文本处理。

<script>
    async function doRequest() {
        let url = 'http://webcode.me';
        let res = await fetch(url);

        if (res.ok) {

            let text = await res.text();

            return text;
        } else {
            return `HTTP error: ${res.status}`;
        }
    }

    doRequest().then(data => {
        console.log(data);
    });

</script>

我们获取 webcode.me 网页的内容。

let url = 'http://webcode.me';
let res = await fetch(url);

fetch 方法仅将 URL 作为参数。在这种情况下,默认请求是 GET 请求。

let text = await res.text();

我们从请求中获取正文作为纯文本。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My html page</title>
</head>
<body>

    <p>
        Today is a beautiful day. We go swimming and fishing.
    </p>
    
    <p>
         Hello there. How are you?
    </p>
    
</body>
</html>

这是我们在浏览器控制台窗口中可以看到的输出。

JS fetch GET 请求带查询参数

在以下示例中,我们向 URL 附加一些查询参数。

<script>
    async function doRequest() {

        let url = new URL('http://httpbin.org/get');
        let params = {'name': 'John Doe', 'occupation': 'John Doe'};
        url.search = new URLSearchParams(params);

        let res = await fetch(url);

        if (res.ok) {

            let text = await res.text();

            return text;
        } else {
            return `HTTP error: ${res.status}`;
        }
    }

    doRequest().then(data => {
        console.log(data);
    });

</script>

我们使用 URLSearchParams 将 JSON 对象转换为合适的 URL 查询形式。

{
  "args": {
    "name": "John Doe", 
    "occupation": "John Doe"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Accept-Language": "en-US,en;q=0.5", 
    "Host": "httpbin.org", 
    "Origin": "null", 
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0", 
    "X-Amzn-Trace-Id": "Root=1-600ff33e-71b89c984ad2878035263a8b"
  }, 
  ...
  "url": "http://httpbin.org/get?name=John+Doe&occupation=John+Doe"
}

我们从 httpbin.org 网页获取此输出。

JS fetch 获取图片

以下示例检索图像并将其显示在页面上。

<script>
    async function doRequest() {
        let url = 'https://dummyimage.com/100x100/499deb/fff';
        let res = await fetch(url);
        let blob = await res.blob(); 

        return blob;
    }

    doRequest().then(blob => {

        let img = document.createElement('img');
        document.body.append(img);

        img.src = URL.createObjectURL(blob);
    });
</script>

该示例使用 dummyimage.com 网页获取图像。这是一个用于测试目的的小测试页面。

let blob = await res.blob(); 

要获取图像数据,我们调用 blob 函数。

let img = document.createElement('img');
document.body.append(img);

我们以编程方式创建 img 标签。

img.src = URL.createObjectURL(blob);

我们使用 createObjectURL 函数创建图像。

JS fetch JSON POST 请求

以下示例生成带有 JSON 数据的 POST 请求。

<script>
    async function doRequest() {

        let url = 'http://httpbin.org/post';
        let data = {'name': 'John Doe', 'occupation': 'John Doe'};

        let res = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
        });

        if (res.ok) {

            // let text = await res.text();
            // return text;

            let ret = await res.json();
            return JSON.parse(ret.data);

        } else {
            return `HTTP error: ${res.status}`;
        }
    }

    doRequest().then(data => {
        console.log(data);
    });

</script>

该请求被发送到 http://httpbin.org/post。

let data = {'name': 'John Doe', 'occupation': 'John Doe'};

这是要发送的数据。

let res = await fetch(url, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
});

我们将 method 参数设置为 POST,并为内容类型选择 application/json。数据被字符串化到 body 参数。

let ret = await res.json();
return JSON.parse(ret.data);

我们将数据作为 JSON 字符串获取,并将其解析为 JSON 对象。

Object { name: "John Doe", occupation: "John Doe" }

JS fetch POST 表单数据

在下面的示例中,我们生成一个包含表单数据的 POST 请求。

使用 application/x-www-form-urlencoded,数据以请求正文的形式发送;键和值以键值元组的形式编码,由 '&' 分隔,键和值之间用 '=' 分隔。

<script>
    async function doRequest() {

        let url = 'http://httpbin.org/post';

        let formData = new FormData();
        formData.append('name', 'John Doe');
        formData.append('occupation', 'gardener');

        let res = await fetch(url, {
            method: 'POST',
            body: formData,
        });

        if (res.ok) {

            let text = await res.text();
            return text;

        } else {
            return `HTTP error: ${res.status}`;
        }
    }

    doRequest().then(data => {
        console.log(data);
    });

</script>

为了以适当的格式生成表单数据,我们使用 FormData 对象。

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "name": "John Doe", 
    "occupation": "gardener"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Accept-Language": "en-US,en;q=0.5", 
    "Content-Length": "305", 
    "Content-Type": "multipart/form-data; ... 
    "Host": "httpbin.org", 
    "Origin": "null", 
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0", 
    "X-Amzn-Trace-Id": "Root=1-600ff649-4cd21c6a503e694211f73b0c"
  }, 
  "json": null, 
  ...
  "url": "http://httpbin.org/post"
}

来源

使用 Fetch API

在本文中,我们使用了 JavaScript fetch API。

作者

我的名字是 Jan Bodnar,我是一位热衷的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我已经撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

查看 所有 JavaScript 教程。