I need to create a form that sends a keyword to the server. Then, my server forwards this keyword to the Amazon server, which returns information such as name, price, photo, etc. After that, I need to send this information to the frontend.
The problem is that Amazon is blocking my axios. I tested with other API and the axios works.
my index.js that gets the keyword and sends to MY server:
const form = document.querySelector('form')
const keywordInput = document.querySelector('[data-key-word-input]')
const keywordResults = document.querySelector('[data-key-word-results]')
form.addEventListener('submit', async (e) => {
e.preventDefault()
let keyword = keywordInput.value.trim()
console.log(keyword)
if (!keyword) {
alert('Enter a valid keyword')
return
}
try {
let response = await fetch(`http://localhost:3000/api/scrape?keyword=${encodeURIComponent(keyword)}`)
let data = await response.json()
keywordResults.innerHTML = ''
if (data.length === 0) {
keywordResults.innerHTML = 'Not found'
return
}
data.forEach(product => {
const productDiv = document.createElement('div')
productDiv.classList.add('product')
productDiv.innerHTML = `
<h3>${product.title}</h3>
<p>Rating: ${product.rating} (${product.reviews} reviews)</p>
<img src="${product.imageUrl}" alt="${product.title}">
`
keywordResults.appendChild(productDiv)
})
}
catch (error) {
console.error('Error', error)
alert('Failed to fetch data from server')
}
})
my server, that sends the keyword to amazon and should send the response from amazon to my index.js:
const express = require('express')
const axios = require('axios')
const { JSDOM } = require('jsdom')
const cors = require('cors')
const app = express()
app.use(cors())
const PORT = process.env.PORT || 3000
app.get('/api/scrape', async (req, res) => {
try {
const keyword = req.query.keyword
console.log('Palavra-chave:', keyword)
const url = `http://www.amazon.com/s?k=${keyword}`
const response = await axios.get(url)
const html = response.data
const dom = new JSDOM(html)
const document = dom.window.document
const products = []
document.querySelectorAll('.s-result-item').forEach((item) => {
const title = item.querySelector('h2').textContent.trim()
const rating = parseFloat(item.querySelector('.a-icon-star-small').textContent.split(' ')[0])
const reviews = parseInt(item.querySelector('.a-size-small').textContent.replace(/[^d]/g, ''))
const imageUrl = item.querySelector('img').getAttribute('src')
products.push({ title, rating, reviews, imageUrl })
})
res.json(products)
} catch (error) {
console.error('Error:', error);
res.status(500).json({ error: 'Internal Server Error', message: error.message });
}
})
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`)
})