在本章中,我们将详细介绍如何使用 Deno 来发送 GET 请求。首先,我们需要了解 Deno 中处理网络请求的基本概念和相关模块。接着,我们会通过实际的例子来展示如何构建一个简单的 GET 请求,并解析返回的数据。
引入所需模块
在 Deno 中,我们主要使用 fetch 函数来发起网络请求。这个函数类似于浏览器中的 fetch API,但可以在 Node.js 和 Deno 环境中使用。为了使用它,我们需要导入 fetch 函数所在的模块。
import { fetch } from "https://deno.land/std@0.149.0/node/fetch.ts";这里我们从 https://deno.land/std 引入了标准库中的 fetch 函数,这样我们可以更方便地与 Node.js 的 fetch API 兼容。如果你只需要 Deno 的原生 fetch 功能,可以直接使用:
import { fetch } from "deno:core";构建一个基本的 GET 请求
接下来,我们来看一下如何使用 fetch 发送一个简单的 GET 请求。下面的代码展示了如何获取一个 JSON 格式的响应数据。
// www.javascriptcn.com code example
async function fetchData(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
const url = 'https://jsonplaceholder.typicode.com/todos/1';
fetchData(url)
.then(data => console.log(data))
.catch(error => console.error('Error:', error));在这个例子中,我们定义了一个名为 fetchData 的异步函数,该函数接收一个 URL 参数。我们使用 await 关键字等待 fetch 返回的 Promise 解析。如果响应的状态码不是成功的状态(例如 200 到 299 之间),则抛出一个错误。最后,我们使用 .json() 方法将响应体转换为 JSON 对象。
处理响应头
除了处理响应体之外,我们有时也需要访问响应头。这可以通过响应对象的 headers 属性来实现。下面的例子展示了如何获取并打印出响应头信息。
// www.javascriptcn.com code example
async function fetchWithHeaders(url) {
const response = await fetch(url);
const headers = response.headers;
console.log('Headers:');
headers.forEach((value, name) => console.log(`${name}: ${value}`));
return response.json();
}
const url = 'https://jsonplaceholder.typicode.com/todos/1';
fetchWithHeaders(url)
.then(data => console.log(data))
.catch(error => console.error('Error:', error));设置请求头
有时候,我们需要向服务器发送一些自定义的请求头。比如,设置一个特定的用户代理或者添加认证信息。我们可以这样做:
// www.javascriptcn.com code example
async function fetchWithOptions(url) {
const options = {
headers: {
'User-Agent': 'My App',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
}
};
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
const url = 'https://jsonplaceholder.typicode.com/todos/1';
fetchWithOptions(url)
.then(data => console.log(data))
.catch(error => console.error('Error:', error));在这个例子中,我们通过传递第二个参数给 fetch 函数来设置请求头。
错误处理
发送网络请求时,错误处理是非常重要的。我们已经看到了一些基本的错误处理方式,例如检查响应状态码。但是,网络请求可能会因为各种原因失败,如超时、DNS 解析失败等。因此,我们应该尽可能全面地处理这些可能的错误情况。
// www.javascriptcn.com code example
async function safeFetch(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
} catch (error) {
console.error('Network request failed:', error);
}
}
const url = 'https://jsonplaceholder.typicode.com/todos/1';
safeFetch(url)
.then(data => console.log(data))
.catch(error => console.error('Error:', error));在这个例子中,我们使用 try-catch 结构来捕获并处理可能出现的所有错误,包括那些在 fetch 调用过程中发生的错误。
通过以上步骤,你应该能够熟练地使用 Deno 来发送 GET 请求,并处理相关的响应数据。希望这些示例对你有所帮助!