Chuyển đổi lệnh curl thành mã JavaScript - Tạo mã JavaScript fetch/axios sẵn sàng sử dụng cho các yêu cầu API
// JavaScript code will appear here // Example: // Using fetch API fetch('https://api.example.com/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'test' }) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
Dưới đây là một số lệnh curl phổ biến mà bạn có thể chuyển đổi thành mã JavaScript:
curl https://api.example.com/users
curl -X POST -H "Content-Type: application/json" -d '{"name":"John","email":"[email protected]"}' https://api.example.com/users
curl -X PUT -H "Authorization: Bearer token123" -d '{"status":"active"}' https://api.example.com/users/1
curl -X DELETE https://api.example.com/users/1
curl -H "X-API-Key: abc123" -H "Accept: application/json" https://api.example.com/data
JavaScript cung cấp nhiều cách để thực hiện các yêu cầu HTTP. Dưới đây là các mẫu phổ biến sử dụng cả Fetch API và Axios:
const formData = new FormData(); formData.append('file', document.querySelector('#fileInput').files[0]); fetch('https://api.example.com/upload', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_TOKEN_HERE' }, body: formData }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
const controller = new AbortController(); const signal = controller.signal; // Set timeout of 5 seconds const timeoutId = setTimeout(() => controller.abort(), 5000); fetch('https://api.example.com/data', { method: 'GET', signal: signal }) .then(response => { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } clearTimeout(timeoutId); return response.json(); }) .then(data => console.log(data)) .catch(error => { if (error.name === 'AbortError') { console.error('Request timed out'); } else { console.error('Error:', error); } });
Sao chép lệnh curl của bạn → Dán vào hộp nhập liệu → Nhận mã JavaScript ngay lập tức
axios.get('https://api.example.com/data') .then(response => { console.log(response.data); }) .catch(error => { if (error.response) { // Server returned an error status code console.error(`Server error: ${error.response.status}`); console.error(error.response.data); } else if (error.request) { // Request was made but no response received console.error('Network error - no response received'); } else { // Error in request setup console.error('Request error:', error.message); } });
// Using fetch with AbortController const controller = new AbortController(); const signal = controller.signal; // Cancel request after 5 seconds setTimeout(() => controller.abort(), 5000); fetch('https://api.example.com/data', { signal }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => { if (error.name === 'AbortError') { console.log('Request was cancelled'); } else { console.error('Error:', error); } }); // Using axios with CancelToken const source = axios.CancelToken.source(); // Cancel request after 5 seconds setTimeout(() => { source.cancel('User cancelled the request'); }, 5000); axios.get('https://api.example.com/data', { cancelToken: source.token }) .then(response => console.log(response.data)) .catch(error => { if (axios.isCancel(error)) { console.log('Request cancelled:', error.message); } else { console.error('Error:', error); } });
Đ: Trong khi curl là một công cụ dòng lệnh để thực hiện các yêu cầu HTTP, Fetch API của JavaScript cung cấp một giao diện lập trình trong các trình duyệt web và Node.js. Fetch sử dụng Promises để xử lý các thao tác bất đồng bộ, trong khi curl thực thi đồng bộ. Ngoài ra, fetch tự động theo dõi chuyển hướng và không gửi cookie theo mặc định, trong khi curl làm cả hai trừ khi được cấu hình khác.
Đ: Fetch được tích hợp sẵn trong các trình duyệt hiện đại nhưng yêu cầu nhiều mã soạn sẵn hơn cho xử lý lỗi và không tự động phân tích phản hồi JSON. Axios là một thư viện cung cấp API phong phú hơn với phân tích JSON tự động, xử lý lỗi tốt hơn, chặn yêu cầu/phản hồi và hủy yêu cầu tích hợp sẵn. Axios cũng hoạt động nhất quán trên các môi trường trình duyệt và Node.js.
Đ: Các hạn chế CORS (Chia Sẻ Tài Nguyên Giữa Các Nguồn Gốc) áp dụng cho JavaScript dựa trên trình duyệt nhưng không áp dụng cho curl. Khi chuyển đổi lệnh curl sang JavaScript, bạn có thể gặp lỗi CORS nếu máy chủ không bao gồm các header CORS thích hợp. Các giải pháp bao gồm: sử dụng proxy CORS, yêu cầu chủ sở hữu API bật header CORS, triển khai proxy phía máy chủ trong ứng dụng của bạn, hoặc sử dụng Node.js cho các yêu cầu không chạy trong trình duyệt.
Đ: Trong JavaScript dựa trên trình duyệt, bạn không thể bỏ qua xác thực chứng chỉ SSL vì đó là tính năng bảo mật do trình duyệt thực thi. Trong Node.js, bạn có thể đặt tùy chọn rejectUnauthorized: false
trong cấu hình HTTPS agent. Tuy nhiên, điều này không được khuyến khích trong môi trường sản xuất vì nó làm giảm bảo mật. Ví dụ: const https = require('https'); const agent = new https.Agent({rejectUnauthorized: false});
Đ: Để xử lý tải lên tệp trong JavaScript tương tự như cờ -F của curl, sử dụng API FormData. Ví dụ: const formData = new FormData(); formData.append('file', fileInput.files[0]); formData.append('field', 'value'); fetch('https://api.example.com/upload', { method: 'POST', body: formData });
Cách tiếp cận này hoạt động với cả fetch và axios.
Đ: Với Fetch API, sử dụng AbortController với setTimeout: const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 5000); fetch(url, { signal: controller.signal });
Với axios, sử dụng tùy chọn timeout: axios.get(url, { timeout: 5000 });
Cả hai cách tiếp cận đều cho phép bạn kiểm soát thời gian chờ trước khi hủy yêu cầu.
Đ: Trong khi curl cung cấp cờ -v/--verbose để biết thông tin yêu cầu/phản hồi chi tiết, JavaScript cung cấp các công cụ gỡ lỗi khác nhau. Trong trình duyệt, sử dụng tab Network trong DevTools để kiểm tra yêu cầu, header, tải trọng và thời gian. Đối với gỡ lỗi lập trình, bạn có thể sử dụng bộ chặn axios để ghi nhật ký chi tiết yêu cầu/phản hồi hoặc triển khai ghi nhật ký tùy chỉnh với fetch. Trong Node.js, bạn có thể sử dụng thư viện như 'http-debug' hoặc đặt biến môi trường NODE_DEBUG=http.
Hiểu các lệnh curl là điều cần thiết cho kiểm thử API hiệu quả với JavaScript. Dưới đây là tham khảo nhanh về các tùy chọn curl phổ biến mà bộ chuyển đổi của chúng tôi hỗ trợ:
curl [options] [URL]
-X, --request METHOD
: Specify request method (GET, POST, PUT, DELETE, etc.)-H, --header LINE
: Add header to the request-d, --data DATA
: Send data in POST request-F, --form CONTENT
: Submit form data-u, --user USER:PASSWORD
: Server user and password-k, --insecure
: Allow insecure server connections-I, --head
: Show document info only-v, --verbose
: Make the operation more verbose-s, --silent
: Silent mode--connect-timeout SECONDS
: Maximum time for connectionBộ chuyển đổi JavaScript của chúng tôi xử lý các lệnh curl phức tạp bao gồm nhiều header, xác thực, tải trọng dữ liệu và các tùy chọn khác nhau. Chỉ cần dán lệnh curl của bạn và nhận mã JavaScript sạch, hiện đại sử dụng Fetch API hoặc Axios.
Khi làm việc với Fetch API hoặc Axios của JavaScript, hãy tuân theo các thực hành tốt nhất sau đây để tương tác API hiệu quả và an toàn:
// Using async/await with 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); return data; } catch (error) { console.error('Fetch error:', error); } } // Using async/await with axios async function fetchDataWithAxios() { try { const response = await axios.get('https://api.example.com/data'); console.log(response.data); return response.data; } catch (error) { console.error('Axios error:', error); } }
async function fetchWithRetry(url, options = {}, retries = 3, backoff = 300) { try { const response = await fetch(url, options); return response; } catch (error) { if (retries <= 1) throw error; await new Promise(resolve => setTimeout(resolve, backoff)); return fetchWithRetry(url, options, retries - 1, backoff * 2); } }
// Create configurable API client with axios const apiClient = axios.create({ baseURL: 'https://api.example.com', timeout: 10000, headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }); // Add request interceptors apiClient.interceptors.request.use(config => { // Do something before request is sent const token = localStorage.getItem('token'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }, error => { return Promise.reject(error); }); // Add response interceptors apiClient.interceptors.response.use(response => { // Any status code within 2xx range return response; }, error => { // Handle 401 Unauthorized errors if (error.response && error.response.status === 401) { console.log('Unauthorized, please login again'); } return Promise.reject(error); }); // Use the API client apiClient.get('/users') .then(response => console.log(response.data)) .catch(error => console.error(error));
// Using Promise.all with fetch async function fetchMultipleResources() { try { const [users, products, orders] = await Promise.all([ fetch('https://api.example.com/users').then(res => res.json()), fetch('https://api.example.com/products').then(res => res.json()), fetch('https://api.example.com/orders').then(res => res.json()) ]); console.log({ users, products, orders }); return { users, products, orders }; } catch (error) { console.error('Error fetching data:', error); } } // Using axios.all for concurrent requests async function fetchMultipleResourcesWithAxios() { try { const [users, products, orders] = await axios.all([ axios.get('https://api.example.com/users'), axios.get('https://api.example.com/products'), axios.get('https://api.example.com/orders') ]); console.log({ users: users.data, products: products.data, orders: orders.data }); } catch (error) { console.error('Error fetching data:', error); } }
// Simple in-memory cache implementation const cache = new Map(); async function fetchWithCache(url, options = {}, ttl = 60000) { const cacheKey = `${url}-${JSON.stringify(options)}`; // Check cache const cachedItem = cache.get(cacheKey); if (cachedItem && Date.now() < cachedItem.expiry) { console.log('Using cached data'); return cachedItem.data; } // If no cache or expired, make the request const response = await fetch(url, options); const data = await response.json(); // Update cache cache.set(cacheKey, { data, expiry: Date.now() + ttl }); return data; }