將 curl 命令轉換為 JavaScript 程式碼 - 為 API 請求生成即用型 JavaScript fetch/axios 程式碼
// 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));
以下是一些可以轉換為 JavaScript 程式碼的常見 curl 命令:
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 提供多種方式來發出 HTTP 請求。以下是使用 Fetch API 和 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); } });
複製您的 curl 命令 → 貼到輸入框 → 立即獲取 JavaScript 程式碼
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); } });
答:雖然 curl 是用於發出 HTTP 請求的命令行工具,但 JavaScript 的 fetch API 在網頁瀏覽器和 Node.js 中提供了程式化介面。Fetch 使用 Promise 處理非同步操作,而 curl 則同步執行。此外,fetch 會自動跟隨重定向且默認不發送 cookie,而 curl 除非另行配置,否則會執行這兩項操作。
答:Fetch 內建於現代瀏覽器中,但需要更多樣板代碼進行錯誤處理,且不會自動解析 JSON 回應。Axios 是一個庫,提供更豐富的 API,具有自動 JSON 解析、更好的錯誤處理、請求/回應攔截和內建請求取消功能。Axios 在瀏覽器和 Node.js 環境中也能一致運作。
答:CORS(跨來源資源共享)限制適用於基於瀏覽器的 JavaScript,但不適用於 curl。將 curl 命令轉換為 JavaScript 時,如果伺服器未包含適當的 CORS 標頭,您可能會遇到 CORS 錯誤。解決方案包括:使用 CORS 代理、請求 API 擁有者啟用 CORS 標頭、在應用程式中實現伺服器端代理,或使用 Node.js 進行不在瀏覽器中運行的請求。
答:在基於瀏覽器的 JavaScript 中,您無法繞過 SSL 憑證驗證,因為這是瀏覽器強制執行的安全功能。在 Node.js 中,您可以在 HTTPS 代理配置中設置 rejectUnauthorized: false
選項。但是,強烈建議在生產環境中不要這樣做,因為它會損害安全性。例如:const https = require('https'); const agent = new https.Agent({rejectUnauthorized: false});
答:要在 JavaScript 中處理類似於 curl 的 -F 標誌的檔案上傳,請使用 FormData API。例如:const formData = new FormData(); formData.append('file', fileInput.files[0]); formData.append('field', 'value'); fetch('https://api.example.com/upload', { method: 'POST', body: formData });
這種方法適用於 fetch 和 axios。
答:使用 fetch API,結合 AbortController 和 setTimeout:const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 5000); fetch(url, { signal: controller.signal });
使用 axios,使用 timeout 選項:axios.get(url, { timeout: 5000 });
這兩種方法都允許您控制等待取消請求的時間。
答:雖然 curl 提供 -v/--verbose 標誌來獲取詳細的請求/回應信息,但 JavaScript 提供了不同的調試工具。在瀏覽器中,使用 DevTools 的 Network 標籤檢查請求、標頭、負載和計時。對於程式化調試,您可以使用 axios 攔截器記錄請求/回應詳細信息,或使用 fetch 實現自訂日誌記錄。在 Node.js 中,您可以使用 'http-debug' 等庫或設置 NODE_DEBUG=http 環境變數。
了解 curl 命令對於使用 JavaScript 進行有效的 API 測試至關重要。以下是我們的轉換器支援的常見 curl 選項的快速參考:
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 connection我們的 JavaScript 轉換器處理複雜的 curl 命令,包括多個標頭、身份驗證、資料負載和各種選項。只需貼上您的 curl 命令,即可獲得使用 Fetch API 或 Axios 的乾淨、現代的 JavaScript 程式碼。
使用 JavaScript 的 Fetch API 或 Axios 時,請遵循這些最佳實踐,以實現高效且安全的 API 互動:
// 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; }