Curl 轉 JavaScript 轉換器

將 curl 命令轉換為 JavaScript 程式碼 - 為 API 請求生成即用型 JavaScript fetch/axios 程式碼

隱私聲明: 這款專業工具提供安全轉換為 JavaScript 程式碼,具有企業級隱私保護。我們不會儲存您提交的任何資料,確保您的 API 開發工作完全保密。

JavaScript 程式碼產生器

// 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 API 測試的常見 curl 命令

以下是一些可以轉換為 JavaScript 程式碼的常見 curl 命令:

JavaScript Fetch 和 Axios 範例

JavaScript 提供多種方式來發出 HTTP 請求。以下是使用 Fetch API 和 Axios 的常見模式:

使用 JavaScript Fetch 上傳檔案

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));

帶有逾時和錯誤處理的 JavaScript Fetch

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);
  }
});

如何使用 JavaScript 程式碼轉換器

1. 基本用法

複製您的 curl 命令 → 貼到輸入框 → 立即獲取 JavaScript 程式碼

2. 實現適當的錯誤處理

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);
    }
  });

3. 使用請求取消以獲得更好的用戶體驗

// 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);
  }
});

關於 JavaScript HTTP 請求的常見問題

問:JavaScript 的 fetch API 與 curl 有何不同?

答:雖然 curl 是用於發出 HTTP 請求的命令行工具,但 JavaScript 的 fetch API 在網頁瀏覽器和 Node.js 中提供了程式化介面。Fetch 使用 Promise 處理非同步操作,而 curl 則同步執行。此外,fetch 會自動跟隨重定向且默認不發送 cookie,而 curl 除非另行配置,否則會執行這兩項操作。

問:fetch 和 axios 之間的主要區別是什麼?

答:Fetch 內建於現代瀏覽器中,但需要更多樣板代碼進行錯誤處理,且不會自動解析 JSON 回應。Axios 是一個庫,提供更豐富的 API,具有自動 JSON 解析、更好的錯誤處理、請求/回應攔截和內建請求取消功能。Axios 在瀏覽器和 Node.js 環境中也能一致運作。

問:將 curl 命令轉換為 JavaScript 時如何處理 CORS 問題?

答:CORS(跨來源資源共享)限制適用於基於瀏覽器的 JavaScript,但不適用於 curl。將 curl 命令轉換為 JavaScript 時,如果伺服器未包含適當的 CORS 標頭,您可能會遇到 CORS 錯誤。解決方案包括:使用 CORS 代理、請求 API 擁有者啟用 CORS 標頭、在應用程式中實現伺服器端代理,或使用 Node.js 進行不在瀏覽器中運行的請求。

問:如何在 JavaScript 中模擬 curl 的 -k/--insecure 標誌?

答:在基於瀏覽器的 JavaScript 中,您無法繞過 SSL 憑證驗證,因為這是瀏覽器強制執行的安全功能。在 Node.js 中,您可以在 HTTPS 代理配置中設置 rejectUnauthorized: false 選項。但是,強烈建議在生產環境中不要這樣做,因為它會損害安全性。例如:const https = require('https'); const agent = new https.Agent({rejectUnauthorized: false});

問:如何在 JavaScript 中處理類似於 curl 的 -F 標誌的檔案上傳?

答:要在 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。

問:如何在 JavaScript 中設置類似於 curl 的 --connect-timeout 的請求逾時?

答:使用 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 的詳細模式相比,如何在 JavaScript 中調試網路請求?

答:雖然 curl 提供 -v/--verbose 標誌來獲取詳細的請求/回應信息,但 JavaScript 提供了不同的調試工具。在瀏覽器中,使用 DevTools 的 Network 標籤檢查請求、標頭、負載和計時。對於程式化調試,您可以使用 axios 攔截器記錄請求/回應詳細信息,或使用 fetch 實現自訂日誌記錄。在 Node.js 中,您可以使用 'http-debug' 等庫或設置 NODE_DEBUG=http 環境變數。

JavaScript API 測試的 Curl 命令參考

了解 curl 命令對於使用 JavaScript 進行有效的 API 測試至關重要。以下是我們的轉換器支援的常見 curl 選項的快速參考:

基本 curl 語法

curl [options] [URL]

常見 curl 選項

轉換複雜的 curl 命令

我們的 JavaScript 轉換器處理複雜的 curl 命令,包括多個標頭、身份驗證、資料負載和各種選項。只需貼上您的 curl 命令,即可獲得使用 Fetch API 或 Axios 的乾淨、現代的 JavaScript 程式碼。

JavaScript HTTP 最佳實踐

使用 JavaScript 的 Fetch API 或 Axios 時,請遵循這些最佳實踐,以實現高效且安全的 API 互動:

1. 使用 async/await 以獲得更好的可讀性

// 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);
  }
}

2. 實現請求重試機制

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);
  }
}

3. 創建可重複使用的 API 客戶端

// 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));

4. 處理並發請求

// 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);
  }
}

5. 實現請求快取

// 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;
}
" } }, { "@type": "Question", "name": "如何將帶有檔案上傳的 curl 命令轉換為 JavaScript?", "acceptedAnswer": { "@type": "Answer", "text": "對於 JavaScript 中的檔案上傳,您需要使用 FormData API。我們的轉換器處理帶有 -F 或 --form 選項的 curl 命令,並使用 fetch 或 axios 生成適當的 JavaScript 程式碼。" } } ] }