Node.js 中使用 node-fetch 库设置 User-Agent 示例
以下是使用 node-fetch 库在 JavaScript 中设置 User-Agent 的示例:
const fetch = require('node-fetch');
const url = 'https://example.com';
const options = {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
};
fetch(url, options)
.then(response => {
if (response.ok) {
return response.text();
}
throw new Error('Network response was not ok.');
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
在上面的示例中,我们使用 node-fetch 向 https://example.com URL 发送请求,并设置了自定义的 User-Agent 头部。然后,我们检查响应是否正常,如果正常,将响应数据打印到控制台。如果 fetch 过程出现错误,我们会在控制台中打印错误消息。
原文地址: https://www.cveoy.top/t/topic/oRoL 著作权归作者所有。请勿转载和采集!