Khắc phục lỗi proxy khi lập trình Python, Node.js và cURL
6 tháng 7, 2026
Giới thiệu
Proxy được dùng rộng rãi trong các ứng dụng lấy dữ liệu, thử nghiệm API hay thực hiện các tác vụ tự động. Tuy nhiên, khi làm việc với proxy thường gặp phải nhiều lỗi:
- Connection timed out
- Proxy authentication error
- DNS resolution fail
- HTTP 403/429
- IP leak
Bài viết này sẽ hướng dẫn cách cấu hình proxy đúng cách trong Python, Node.js và cURL, cách debug thông qua logs, và mẹo tối ưu hiệu suất.
1. Cấu hình proxy trong Python
Python cung cấp nhiều thư viện hỗ trợ HTTP, nhưng cách làm phổ biến nhất là dùng requests và httpx.
1.1 Sử dụng requests
import requests
proxies = {
"http": "http://user:pass@host:port",
"https": "https://user:pass@host:port",
}
try:
r = requests.get("https://api.ipify.org?format=json", proxies=proxies, timeout=10)
r.raise_for_status()
print(r.json())
except requests.exceptions.RequestException as e:
TIFF = str(e)
print("Error:", TIFF)
Tip: Nếu proxy không yêu cầu mật khẩu, bỏ
user:pass@.
1.2 Sử dụng httpx
import httpx
proxies = {
"http://": "http://host:port",
"https://": "https://host:port",
}
with httpx.Client(proxies=proxies, timeout=10) as client:
try:
resp = client.get("https://api.ipify.org?format=json")
resp.raise_for_status()
print(resp.json())
except httpx.RequestError as exc:
print("Error:", exc)
httpx hỗ trợ proxy SOCKS5 Inteface:
proxies = {
"http://": "socks5://host:port",
"https://": "socks5://host:port",
}
1.3 Debug trong Python
- Dùng
logging:
import logging
logging.basicConfig(level=logging.DEBUG)
- Kiểm tra header
ViavàX-Forwarded-Forđể xác nhận proxy. - Sử dụng
pyaesđể kiểm tra độ bảo mật.
2. Cấu hình proxy trong Node.js
Node.js thường dùng axios, node-fetch hoặc request (cũ).
2.1 Sử dụng axios
const axios = require('axios');
const instance = axios.create({
proxy: {
host: 'host',
port: 8000,
auth: {
username: 'user',
password: 'pass'
}
},
timeout: 10000
});
instance.get('https://api.ipify.org?format=json')
.then(res => console.log(res.data))
.catch(err => console.error('Error:', err.message));
2.2 Sử dụng node-fetch với proxy-agent
const fetch = require('node-fetch');
const HttpsProxyAgent = require('https-proxy-agent');
const proxy = 'http://user:pass@host:port';
const agent = new HttpsProxyAgent(proxy);
fetch('https://api.ipify.org?format=json', { agent })
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error('Error:', err));
###office 2.3 Debug Node.js
- Sử dụng
NODE_DEBUG=httpđể xem lại HTTP requests. - Kiểm tra biến môi trường
HTTPS_PROXYvàHTTP_PROXY.
3. Cấu hình proxy trong cURL
cURL là công cụ dòng lệnh mạnh mẽ, rất được dùng trong script.
curl -x http://user:pass@host:port https://api.ipify.org?format=json
Existem opções avançadas:
--proxy-basicđể bật basic auth.--proxyまでđể đổi proxy mỗi lần.--proxy-ssl-verify-peer=nonếu cần bỏ quaโอ่ TLS.
3.1 Kiểm tra lỗi cURL
echo $?
Xác định mã lỗi cURL:
- 7: Failed to connect to host
- 28: Operation timeout
- 5: Could not resolve host
Giải pháp: kiểm tra đường dẫn proxy, DNS, timeout.
4. Vấn đề thường gặp và cách khprozess
| Lỗi | Nguyên nhân | Giải pháp |
|---|---|---|
| Connection timed out | Proxy không phản hồi | Kiểm tra port, tăng timeout, chuyển proxy |
| 403 Forbidden | IP bị chặn | Xoay IP, dùng residential proxy |
| 429 Too Many Requests | Rate limit | Thêm delay, giảm tần suất, rotating proxy |
| DNS resolution fail | DNS không đúng proxy | Đặt dns_server= trong cấu hình, sử dụng DNS over TLS |
| IP leak | Proxy không bảo mật | Kiểm tra curl -I https://www.whatsmyip.org/들은 |
5. Tối ưu hiệu suất proxy
- Chọn địa điểm địa lý: Giảm latency bằng cách đặt proxy gần API.
- Sử dụng TCP Keep-Alive: Giữ kết nối mở cho các request liên tiếp.
- Batch requests: Gộp request để giảm overhead.
- Sử dụng
async/await: Tránh blocking I/O. - Cache phản hồi: Tránh request lặp.
- Debug logs: Kiểm tra logs để xác định bottle neck.
6. Ví dụ thực tế: Scraper tốc độ cao (Python + asyncio + httpx)
import asyncio
import httpx
proxys = [
"http://user:pass@proxy1:port",
"http://user:pass@proxy2:port",
# ... thêm proxy
]
async def fetch(url, proxy):
async with httpx.AsyncClient(proxies={"http://": proxy, "https://": proxy}, timeout=10) as client:
try:
r = await client.get(url)
r.raise_for_status()
return r.text
except httpx.HTTPError as e:
print(f"{proxy} Bail: {e}")
return None
async def main():
urls = [f"https://example.com/page{i}" for i in range(100)]
tasks = []
for i, url in enumerate(urls):
proxy = proxys[i % len(proxys)]
tasks.append(asyncio.create_task(fetch(url, proxy)))
results = await asyncio.gather(*tasks)
print("Fetched", len([r for r in results if r]))
asyncio.run(main())
Result: với 5 proxy, khối lượng 100 request chạy trong vòng 20-30s.
7. Kết luận
- Cấu hình đúng proxy: xác định đúng kiểu (HTTP, HTTPS, SOCKS5), đúng địa chỉ, port và auth.
- жі debugging: dùng logs, kiểm tra header, và mã lỗi.
- Tối ưu: lựa chọn địa điểm, Keep-Alive, async.
- Sử dụng proxy chất lượng (như RoProxy) giúp giảm latency, tránh IP ban và bảo vệ dữ liệu.
Hy vọng bài viết giúp bạn vượt qua những rắc rối thường gặp khi làm việc với proxy.