I’m getting a 400 error consistently when I try to use this API through JS (Fetch)
Here is my code…
Have replaced API key with ‘XXX’ but I am 1000% sure this part is correct…
async function fetchData() {
const options = {
method: ‘POST’,
headers: {
‘content-type’: ‘application/json’,
‘X-RapidAPI-Key’: 'XXX,
‘X-RapidAPI-Host’: ‘ebay-average-selling-price.p.rapidapi.com’
},
body: {
keywords: ‘iPhone’,
excluded_keywords: ‘locked cracked case box read LCD’,
max_search_results: ‘240’,
category_id: ‘9355’,
remove_outliers: true,
site_id: ‘0’,
aspects: [
{
name: ‘Model’,
value: ‘Apple iPhone X’
},
{
name: ‘LH_ItemCondition’,
value: ‘3000’
},
{
name: ‘Network’,
value: ‘Unlocked’
},
{
name: ‘Storage Capacity’,
value: ‘64 GB’
}
]
}
};
const res = await fetch(‘https://ebay-average-selling-price.p.rapidapi.com/findCompletedItems’, options)
const record = await res.json()
console.log (‘record’, record)
}
fetchData();
Nehmen Sie an der Diskussion teil - fügen Sie unten einen Kommentar hinzu:
In Javascript,
Fetch
expects the request body to be in string format.Found the issue. When you’re sending body data through native fetch, you need to stringify the body data. Here is updated code that I tested and works:
const KEY = ‘XXX’;
var bodyData = JSON.stringify({
“keywords”: “iPhone”,
“excluded_keywords”: “locked cracked case box read LCD face”,
“max_search_results”: “240”,
“category_id”: “9355”,
“max_pages”: “1”,
“remove_outliers”: true,
“aspects”: [
{
“name”: “Model”,
“value”: “Apple iPhone X”
},
{
“name”: “LH_ItemCondition”,
“value”: “3000”
},
{
“name”: “Network”,
“value”: “Unlocked”
},
{
“name”: “Storage Capacity”,
“value”: “64 GB”
}
]
});
const headers = {
“Content-Type”: “application/json”,
“X-RapidAPI-Host”: “ebay-average-selling-price.p.rapidapi.com”,
“X-RapidAPI-Key”: KEY
}
var requestOptions = {
method: ‘POST’,
body: bodyData,
headers: headers
};
fetch(“https://ebay-average-selling-price.p.rapidapi.com/findCompletedItems”, requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log(‘error’, error));
I’ll look into this and get back to you by the end of the day.