המר פקודות curl לקוד JavaScript - צור קוד JavaScript fetch/axios מוכן לשימוש עבור בקשות 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));
הנה כמה פקודות curl נפוצות שתוכל להמיר לקוד 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 מציע מספר דרכים לביצוע בקשות 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, Fetch API של JavaScript מספק ממשק תכנותי בתוך דפדפנים ו-Node.js. Fetch משתמש ב-Promises לטיפול בפעולות אסינכרוניות, בעוד ש-curl מבצע באופן סינכרוני. בנוסף, fetch עוקב אחר הפניות באופן אוטומטי ואינו שולח עוגיות כברירת מחדל, בעוד ש-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, אתה יכול להגדיר את האפשרות rejectUnauthorized: false
בתצורת סוכן HTTPS. עם זאת, זה מאוד לא מומלץ בייצור כיוון שזה מסכן את האבטחה. דוגמה: const https = require('https'); const agent = new https.Agent({rejectUnauthorized: false});
ת: כדי לטפל בהעלאות קבצים ב-JavaScript בדומה לדגל -F של curl, השתמש ב-API של FormData. לדוגמה: 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 מספק כלי ניפוי שונים. בדפדפנים, השתמש בלשונית Network בכלי המפתח כדי לבחון בקשות, כותרות, מטענים, ותזמון. לניפוי תכנותי, אתה יכול להשתמש ביירוטי axios לרישום פרטי בקשה/תגובה או ליישם רישום מותאם אישית עם fetch. ב-Node.js, אתה יכול להשתמש בספריות כמו 'http-debug' או להגדיר את משתנה הסביבה NODE_DEBUG=http.
הבנת פקודות curl חיונית לבדיקת API יעילה עם JavaScript. הנה מדריך מהיר לאפשרויות 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 שלך וקבל קוד JavaScript נקי ומודרני באמצעות Fetch API או Axios.
בעבודה עם Fetch API או Axios של JavaScript, עקוב אחר שיטות מומלצות אלה לאינטראקציות 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; }