Skip to main content
⚡ Calmops

浏览器Console发送HTTP请求完整指南

概述

在浏览器Console中发送HTTP请求是前端开发者的必备技能,可以用于测试API、调试接口等。

使用Fetch API(推荐)

GET请求

// 简单GET请求
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

// 异步await写法
(async () => {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  console.log(data);
})();

POST请求

// POST JSON数据
fetch('https://api.example.com/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'John',
    email: '[email protected]'
  })
})
.then(response => response.json())
.then(data => console.log(data));

// POST Form数据
const formData = new FormData();
formData.append('username', 'john');
formData.append('email', '[email protected]');

fetch('https://api.example.com/users', {
  method: 'POST',
  body: formData
})
.then(response => response.json())
.then(data => console.log(data));

带认证的请求

// 使用Bearer Token
fetch('https://api.example.com/protected', {
  headers: {
    'Authorization': 'Bearer YOUR_TOKEN_HERE'
  }
})
.then(response => response.json())
.then(data => console.log(data));

// 使用Cookie
fetch('https://api.example.com/user', {
  credentials: 'include'
})
.then(response => response.json())
.then(data => console.log(data));

完整示例

// 封装请求函数
async function sendRequest(url, options = {}) {
  const defaultOptions = {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_TOKEN'
    }
  };
  
  try {
    const response = await fetch(url, { ...defaultOptions, ...options });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const contentType = response.headers.get('content-type');
    if (contentType && contentType.includes('application/json')) {
      return await response.json();
    }
    
    return await response.text();
    
  } catch (error) {
    console.error('Request failed:', error);
    throw error;
  }
}

// 使用示例
sendRequest('https://api.example.com/data')
  .then(data => console.log(data));

sendRequest('https://api.example.com/users', {
  method: 'POST',
  body: JSON.stringify({ name: 'John' })
})
.then(data => console.log(data));

使用XMLHttpRequest

// GET请求
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(JSON.parse(xhr.responseText));
  }
};

xhr.send();

// POST请求
const xhrPost = new XMLHttpRequest();
xhrPost.open('POST', 'https://api.example.com/users', true);
xhrPost.setRequestHeader('Content-Type', 'application/json');

xhrPost.onreadystatechange = function() {
  if (xhrPost.readyState === 4 && xhrPost.status === 201) {
    console.log(JSON.parse(xhrPost.responseText));
  }
};

xhrPost.send(JSON.stringify({
  name: 'John',
  email: '[email protected]'
}));

实用技巧

1. 快速测试API

// 在Console中直接运行
await fetch('https://jsonplaceholder.typicode.com/posts/1').then(r => r.json())

2. 发送文件

// 选择文件
const input = document.createElement('input');
input.type = 'file';
input.onchange = async e => {
  const file = e.target.files[0];
  const formData = new FormData();
  formData.append('file', file);
  
  const response = await fetch('/api/upload', {
    method: 'POST',
    body: formData
  });
  console.log(await response.json());
};
input.click();

3. 下载文件

// 下载为文件
async function downloadJSON(data, filename = 'data.json') {
  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
}

// 使用
fetch('https://api.example.com/data')
  .then(r => r.json())
  .then(data => downloadJSON(data, 'result.json'));

4. 模拟各种HTTP方法

const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'];

methods.forEach(method => {
  window[method.toLowerCase()] = (url, data = null) => {
    const options = { method };
    if (data) {
      options.body = JSON.stringify(data);
      options.headers = { 'Content-Type': 'application/json' };
    }
    return fetch(url, options).then(r => r.json());
  };
});

// 然后可以直接使用
get('https://api.example.com/data')
post('https://api.example.com/users', { name: 'John' })
put('https://api.example.com/users/1', { name: 'Jane' })
delete('https://api.example.com/users/1')

错误处理

async function safeRequest(url, options = {}) {
  try {
    const response = await fetch(url, {
      ...options,
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      }
    });
    
    if (!response.ok) {
      const error = await response.json().catch(() => ({}));
      throw new Error(error.message || `HTTP ${response.status}`);
    }
    
    return await response.json();
    
  } catch (error) {
    console.error('Request Error:', {
      url,
      message: error.message,
      timestamp: new Date().toISOString()
    });
    throw error;
  }
}

// 使用
safeRequest('https://api.example.com/data')
  .then(data => console.log(data))
  .catch(err => console.error(err));

常见问题

CORS问题

如果遇到CORS错误,可以:

  1. 后端添加CORS头
  2. 使用代理服务器
  3. 安装CORS Unblock插件(仅开发用)

超时设置

// 使用AbortController设置超时
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);

fetch('https://api.example.com/slow', {
  signal: controller.signal
})
.then(response => {
  clearTimeout(timeoutId);
  return response.json();
})
.catch(error => {
  if (error.name === 'AbortError') {
    console.log('Request timed out');
  }
});

Comments