Konversi perintah curl ke kode JavaScript - Hasilkan kode JavaScript fetch/axios siap pakai untuk permintaan 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));
Berikut adalah beberapa perintah curl umum yang dapat Anda konversi ke kode 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 menawarkan beberapa cara untuk membuat permintaan HTTP. Berikut adalah pola umum menggunakan Fetch API dan 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); } });
Salin perintah curl Anda → Tempel ke kotak input → Dapatkan kode JavaScript secara instan
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); } });
J: Sementara curl adalah alat command-line untuk membuat permintaan HTTP, fetch API JavaScript menyediakan antarmuka terprogram dalam browser web dan Node.js. Fetch menggunakan Promise untuk menangani operasi asinkron, sedangkan curl dieksekusi secara sinkron. Selain itu, fetch secara otomatis mengikuti pengalihan dan tidak mengirim cookie secara default, sementara curl melakukan keduanya kecuali dikonfigurasi sebaliknya.
J: Fetch sudah terpasang di browser modern tetapi memerlukan lebih banyak boilerplate untuk penanganan kesalahan dan tidak secara otomatis mengurai respons JSON. Axios adalah library yang menyediakan API yang lebih kaya fitur dengan penguraian JSON otomatis, penanganan kesalahan yang lebih baik, intersepsi permintaan/respons, dan pembatalan permintaan bawaan. Axios juga bekerja secara konsisten di lingkungan browser dan Node.js.
J: Pembatasan CORS (Cross-Origin Resource Sharing) berlaku untuk JavaScript berbasis browser tetapi tidak untuk curl. Saat mengkonversi perintah curl ke JavaScript, Anda mungkin mengalami kesalahan CORS jika server tidak menyertakan header CORS yang sesuai. Solusinya termasuk: menggunakan proxy CORS, meminta pemilik API untuk mengaktifkan header CORS, mengimplementasikan proxy sisi server di aplikasi Anda, atau menggunakan Node.js untuk permintaan yang tidak berjalan di browser.
J: Dalam JavaScript berbasis browser, Anda tidak dapat melewati validasi sertifikat SSL karena ini adalah fitur keamanan yang diterapkan oleh browser. Di Node.js, Anda dapat mengatur opsi rejectUnauthorized: false
dalam konfigurasi agen HTTPS. Namun, ini sangat tidak disarankan dalam produksi karena membahayakan keamanan. Contoh: const https = require('https'); const agent = new https.Agent({rejectUnauthorized: false});
J: Untuk menangani unggahan file di JavaScript mirip dengan flag -F curl, gunakan API FormData. Contoh: const formData = new FormData(); formData.append('file', fileInput.files[0]); formData.append('field', 'value'); fetch('https://api.example.com/upload', { method: 'POST', body: formData });
Pendekatan ini berfungsi dengan fetch dan axios.
J: Dengan fetch API, gunakan AbortController dengan setTimeout: const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 5000); fetch(url, { signal: controller.signal });
Dengan axios, gunakan opsi timeout: axios.get(url, { timeout: 5000 });
Kedua pendekatan memungkinkan Anda mengontrol berapa lama menunggu sebelum membatalkan permintaan.
J: Sementara curl menawarkan flag -v/--verbose untuk informasi permintaan/respons terperinci, JavaScript menyediakan alat debugging yang berbeda. Di browser, gunakan tab Network di DevTools untuk memeriksa permintaan, header, payload, dan timing. Untuk debugging terprogram, Anda dapat menggunakan interceptor axios untuk mencatat detail permintaan/respons atau mengimplementasikan logging kustom dengan fetch. Di Node.js, Anda dapat menggunakan library seperti 'http-debug' atau mengatur variabel lingkungan NODE_DEBUG=http.
Memahami perintah curl sangat penting untuk pengujian API yang efektif dengan JavaScript. Berikut adalah referensi cepat opsi curl umum yang didukung konverter kami:
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 connectionKonverter JavaScript kami menangani perintah curl kompleks termasuk beberapa header, autentikasi, muatan data, dan berbagai opsi. Cukup tempel perintah curl Anda dan dapatkan kode JavaScript yang bersih dan modern menggunakan Fetch API atau Axios.
Saat bekerja dengan Fetch API atau Axios JavaScript, ikuti praktik terbaik ini untuk interaksi API yang efisien dan aman:
// 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; }