
Anh Tuan
Data Science Expert
Đã xuất bản Sep 24, 2024
Đã cập nhật Sep 23, 2024 · đọc tối thiểu

Axios là một thư viện JavaScript phổ biến được sử dụng để thực hiện các yêu cầu HTTP từ cả trình duyệt và Node.js. Nó đơn giản hóa việc thực hiện các yêu cầu HTTP không đồng bộ và cho phép bạn xử lý phản hồi một cách dễ dàng với lời hứa.
Tính năng:
Trước khi sử dụng Axios, hãy đảm bảo bạn đã có:
Bạn có thể cài đặt Axios bằng npm hoặc yarn:
npm install axios
hoặc
yarn add axios
Đây là cách thực hiện yêu cầu GET đơn giản bằng Axios:
const axios = require('axios');
axios.get('https://httpbin.org/get')
.then(response => {
console.log('Mã trạng thái:', response.status);
console.log('Nội dung phản hồi:', response.data);
})
.catch(error => {
console.error('Lỗi:', error);
});
Hãy lấy dữ liệu từ API và in kết quả:
const axios = require('axios');
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
const posts = response.data;
posts.forEach(post => {
console.log(`${post.title} — ${post.body}`);
});
})
.catch(error => {
console.error('Lỗi:', error);
});
Trong phần này, chúng ta sẽ tích hợp CapSolver với Axios để bỏ qua CAPTCHA. CapSolver cung cấp API để giải quyết CAPTCHA như ReCaptcha V3 và captcha.
Chúng ta sẽ trình bày cách giải quyết ReCaptcha V3 với CapSolver và sử dụng giải pháp trong một yêu cầu.
Đầu tiên, hãy cài đặt Axios và CapSolver:
npm install axios
npm install capsolver
Bây giờ, đây là cách giải quyết ReCaptcha V3 và sử dụng giải pháp trong yêu cầu của bạn:
const axios = require('axios');
const CAPSOLVER_KEY = 'YourKey';
const PAGE_URL = 'https://antcpt.com/score_detector';
const PAGE_KEY = '6LcR_okUAAAAAPYrPe-HK_0RULO1aZM15ENyM-Mf';
const PAGE_ACTION = 'homepage';
async function createTask(url, key, pageAction) {
try {
const apiUrl = 'https://api.capsolver.com/createTask';
const payload = {
clientKey: CAPSOLVER_KEY,
task: {
type: 'ReCaptchaV3TaskProxyLess',
websiteURL: url,
websiteKey: key,
pageAction: pageAction
}
};
const headers = {
'Content-Type': 'application/json',
};
const response = await axios.post(apiUrl, payload, { headers });
return response.data.taskId;
} catch (error) {
console.error('Lỗi tạo nhiệm vụ CAPTCHA:', error);
throw error;
}
}
async function getTaskResult(taskId) {
try {
const apiUrl = 'https://api.capsolver.com/getTaskResult';
const payload = {
clientKey: CAPSOLVER_KEY,
taskId: taskId,
};
const headers = {
'Content-Type': 'application/json',
};
let result;
do {
const response = await axios.post(apiUrl, payload, { headers });
result = response.data;
if (result.status === 'ready') {
return result.solution;
}
await new Promise(resolve => setTimeout(resolve, 5000)); // đợi 5 giây trước khi thử lại
} while (true);
} catch (error) {
console.error('Lỗi lấy kết quả CAPTCHA:', error);
throw error;
}
}
function setSessionHeaders() {
return {
'cache-control': 'max-age=0',
'sec-ch-ua': '"Not/A)Brand";v="99", "Google Chrome";v="107", "Chromium";v="107"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': 'Windows',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'sec-fetch-site': 'same-origin',
'sec-fetch-mode': 'navigate',
'sec-fetch-user': '?1',
'sec-fetch-dest': 'document',
'accept-encoding': 'gzip, deflate',
'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,en-US;q=0.7',
};
}
async function main() {
const headers = setSessionHeaders();
console.log('Đang tạo nhiệm vụ CAPTCHA...');
const taskId = await createTask(PAGE_URL, PAGE_KEY, PAGE_ACTION);
console.log(`ID nhiệm vụ: ${taskId}`);
console.log('Đang lấy kết quả CAPTCHA...');
const solution = await getTaskResult(taskId);
const token = solution.gRecaptchaResponse;
console.log(`Giải pháp mã thông báo: ${token}`);
const res = await axios.post('https://antcpt.com/score_detector/verify.php', { 'g-recaptcha-response': token }, { headers });
const response = res.data;
console.log(`Điểm số: ${response.score}`);
}
main().catch(err => {
console.error(err);
});
Để định tuyến yêu cầu của bạn thông qua proxy với Axios:
const axios = require('axios');
axios.get('https://httpbin.org/ip', {
proxy: {
host: 'proxyserver',
port: 8080,
auth: {
username: 'username',
password: 'password'
}
}
})
.then(response => {
console.log('Nội dung phản hồi:', response.data);
})
.catch(error => {
console.error('Lỗi:', error);
});
Bạn có thể xử lý cookie trong Axios bằng cách sử dụng tùy chọn withCredentials:
const axios = require('axios');
axios.get('https://httpbin.org/cookies/set?name=value', { withCredentials: true })
.then(response => {
console.log('Cookie:', response.headers['set-cookie']);
})
.catch(error => {
console.error('Lỗi:', error);
});
Bạn có thể gửi tiêu đề tùy chỉnh và thực hiện yêu cầu POST với Axios:
const axios = require('axios');
const headers = {
'User-Agent': 'Mozilla/5.0 (compatible)',
'Accept-Language': 'en-US,en;q=0.5',
};
const data = {
username: 'testuser',
password: 'testpass',
};
axios.post('https://httpbin.org/post', data, { headers })
.then(response => {
console.log('Phản hồi JSON:', response.data);
})
.catch(error => {
console.error('Lỗi:', error);
});
Với Axios, bạn có thể dễ dàng quản lý các yêu cầu HTTP trong cả môi trường Node.js và trình duyệt. Bằng cách tích hợp nó với CapSolver, bạn có thể bỏ qua CAPTCHA như ReCaptcha V3 và captcha, cho phép truy cập nội dung bị giới hạn.

Anh Tuan
Data Science Expert
Turning task outcomes into actionable insights.
GIỚI THIỆU TÁC GIẢ
Giải quyết các yêu cầu API CAPTCHA chậm bằng các kiểm tra rõ ràng về tạo nhiệm vụ, kiểm tra kết quả, lỗi, hết hạn token và hành động trình duyệt cuối cùng sau khi giải quyết.

Chọn một người giải CAPTCHA để theo dõi sản phẩm bằng cách kiểm tra khả năng phủ sóng thử thách, quan sát sản phẩm toàn diện, nỗ lực tích hợp, chi phí vận hành và hỗ trợ.
