一、前言

node-fetch是一个可以在 Node.js 环境中使用的第三方模块,允许使用类似浏览器中 Fetch API 的语法和功能,方便进行 HTTP 请求。

  • 支持Promise:node-fetch返回的是一个Promise,所以能使用Promise的链式调用语法。
  • 支持基本的HTTP请求方法:包括GET、POST、PUT、DELETE等。
  • 支持请求头设置:包括Content-Type、Authorization等。
  • 支持发送JSON数据:可以轻松地将JSON数据作为请求体发送。
  • 支持异步/同步请求:支持使用async/await处理异步请求,也支持使用Promise的.then()方法。
1
2
3
4
5
6
7
8
9
// 简单的使用示例
const fetch = require('node-fetch');

const url = 'https://api.example.com/data';

fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

二、安装node-fetch

1.在项目根目录下打开终端

1
2
# 安装命令
npm install node-fetch --save

2.使用node-fetch发起请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Node.js 通过 require 导入 node-fetch
const fetch = require('node-fetch');

const url = 'https://api.example.com/data';

// 发起 GET 请求
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

// 发起 POST 请求
const postData = {
key1: 'value1',
key2: 'value2',
};

fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postData),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

3.使用async/await处理异步代码

1
2
3
4
5
6
7
8
9
10
11
const fetchData = async () => {
try {
const response = await fetch(url);
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
};

fetchData();

三、处理HTTP请求的错误响应

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 示例代码
const fetch = require('node-fetch');

const url = 'https://api.example.com/data';

fetch(url)
.then(response => {
if (!response.ok) {
// 如果响应状态码不在200到299范围内,表示请求失败
throw new Error(`HTTP error! Status: ${response.status}, Message: ${response.statusText}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error.message));

四、处理其它错误(网络错误、JSON解析错误等)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 示例代码:使用instanceof检查错误类型
const fetch = require('node-fetch');

const url = 'https://api.example.com/data';

fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}, Message: ${response.statusText}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => {
if (error instanceof fetch.FetchError) {
console.error('Network error:', error.message);
} else if (error instanceof SyntaxError) {
console.error('JSON parsing error:', error.message);
} else {
console.error('Other error:', error.message);
}
});