使用 JavaScript Fetch API 指定请求头

此页面演示了如何使用 fetch API 向 https://www.anye.xyz/ua 发送一个带有自定义 User-Agent 的 GET 请求。

JavaScript 代码


// 目标 URL
const url = 'https://www.anye.xyz/ua';

// 自定义的 User-Agent
const myUserAgent = 'Custom UserAgent/1.0';

// fetch 配置项
const options = {
    method: 'GET', // 请求方法
    headers: {
        // 在这里设置自定义的请求头
        'User-Agent': myUserAgent
    }
};

// 发起请求
fetch(url, options)
    .then(response => {
        // 检查响应是否成功 (状态码 200-299)
        if (!response.ok) {
            throw new Error(`网络请求失败,状态码: ${response.status}`);
        }
        // 保存状态码
        const statusCode = response.status;
        // 将响应体解析为文本格式
        return response.text().then(data => {
            return { data, statusCode };
        });
    })
    .then(({ data, statusCode }) => {
        // 请求成功,处理返回的文本数据
        console.log('服务器响应:', data);
        // 在这里更新页面上的内容
        document.getElementById('response-body').textContent = data;
        document.getElementById('response-status').className = 'status success';
        document.getElementById('response-status').textContent = `请求成功!状态码: ${statusCode}`;
    })
    .catch(error => {
        // 请求过程中发生错误
        console.error('Fetch Error:', error);
        document.getElementById('response-body').textContent = `错误: ${error.message}`;
        document.getElementById('response-status').className = 'status error';
        document.getElementById('response-status').textContent = '请求失败';
    });
        

服务器响应

等待发起请求...
点击上方按钮,服务器响应将显示在这里。