Files
parcer/scraper/src/main.js

41 lines
1.0 KiB
JavaScript
Raw Normal View History

2024-04-16 22:42:26 +05:30
const fastify = require('fastify')();
2024-04-12 12:12:55 +05:30
const scraper = require('./scraper');
2024-04-16 23:48:32 +05:30
const fetch = require('node-fetch');
2024-04-12 12:24:41 +05:30
// Change this later
const corsOptions = {
origin: 'http://localhost:5173'
}
fastify.register(require('@fastify/cors'), corsOptions)
2024-04-16 23:49:05 +05:30
fastify.get('/proxy', async (request, reply) => {
const { url } = request.query;
try {
const response = await fetch(url);
const html = await response.text();
reply.type('text/html').send(html);
} catch (error) {
reply.status(500).send(`Error fetching website: ${error.message}`);
}
});
2024-04-12 12:12:55 +05:30
fastify.post('/scrape', async (request, reply) => {
2024-04-16 23:48:32 +05:30
const { url, selectors } = request.body;
2024-04-12 12:12:55 +05:30
try {
2024-04-16 23:48:32 +05:30
const data = await scraper(url, selectors);
2024-04-12 12:12:55 +05:30
console.log('Scraped data:', data);
reply.send(data);
} catch (error) {
console.error('Error scraping:', error);
reply.status(500).send({ error: 'Failed to scrape data' });
}
});
fastify.listen(3000, (err, address) => {
if (err) throw err;
2024-04-12 12:24:41 +05:30
console.log(`Server listening on ${fastify.server.address().port}`)
2024-04-12 12:12:55 +05:30
});