Nodejs发起HTTP请求模块node-fetch的使用
Nodejs发起HTTP请求模块node-fetch的使用node-fetch
是一个 Node.js 模块,它实现了 WHATWG Fetch Specification,使你可以使用类似于浏览器中的 fetch()
方法来发起 HTTP 请求。下面是一些基本用法示例。
安装
首先,你需要安装 node-fetch
:
npm install node-fetch
基本用法
发起 GET 请求
const fetch = require('node-fetch');
fetch('https://api.example.com/data')
.then(response => response.json()) // 解析响应体为 JSON
.then(data => console.log(data)) // 处理数据
.catch(error => console.error('Error:', error)); // 错误处理
发起 POST 请求
const fetch = require('node-fetch');
const data = { key1: 'value1', key2: 'value2' };
fetch('https://api.example.com/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
设置请求头
const fetch = require('node-fetch');
fetch('https://api.example.com/secure-data', {
headers: {
'Authorization': 'Bearer your-token-here',
'User-Agent': 'MyApp/1.0'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
处理响应状态码
const fetch = require('node-fetch');
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) { // 检查响应是否成功
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
异步/await 语法
你也可以使用 async/await
语法来简化异步代码:
const fetch = require('node-fetch');
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();
这些示例展示了如何使用 node-fetch
发起不同类型的 HTTP 请求,并处理响应。希望这对您有所帮助!
嘿,朋友!说到node-fetch
,这可是个模拟浏览器发起HTTP请求的好工具。首先,别忘了安装它:npm install node-fetch
。
然后,你可以这样用:
const fetch = require('node-fetch');
fetch('https://api.github.com/users/github')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
这段代码就像给GitHub发送了一封信,询问他们的用户信息。等回复一到(也就是Promise解决),我们就打印出来看看。如果路上出了岔子,我们也会知道的!
希望这能帮到你,如果有任何问题,欢迎随时回来提问!
node-fetch
是一个用于 Node.js 环境中实现浏览器 fetch
API 的库。它允许开发者以类似浏览器的方式发起 HTTP 请求。以下是如何安装和使用 node-fetch
的示例。
安装
首先,你需要通过 npm 安装 node-fetch
:
npm install node-fetch
基本使用
发起GET请求
// 导入 node-fetch 模块
const fetch = require('node-fetch');
async function fetchData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error.message);
}
}
fetchData();
发起POST请求
const fetch = require('node-fetch');
async function postData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: 'foo',
userId: 1,
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error.message);
}
}
postData();
解释
- fetch: 这是主要函数,用于发起请求。
- await: 因为
fetch
返回的是一个 Promise,所以使用await
来等待响应。 - response.ok: 检查响应状态是否为成功(例如:200 到 299)。
- response.json(): 将响应体解析为 JSON 格式。
注意事项
- 确保你的 Node.js 版本支持
async/await
。大多数现代版本都支持。 - 如果需要处理更复杂的请求(如文件上传、设置代理等),可以考虑使用
axios
或request
等其他库,它们提供了更多的功能和灵活性。
希望这可以帮助你在 Node.js 中使用 node-fetch
!
node-fetch
是一个在 Node.js 环境中实现浏览器 Fetch API 的库,用于发起 HTTP 请求。首先需要通过 npm 安装:
npm install node-fetch
使用示例:
const fetch = require('node-fetch');
fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
这里我们向 https://api.example.com/data
发起 GET 请求,并处理返回的数据或错误。