Error when trying to fetch from wikipedia - javascript

I'm trying to fetch from the wikipedia api and I get the "Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource" error. I do not know if it has to do with the way I am appending params. I have no experience with that and I just googled a solution. I tested the parameters on postman so I know it's the right data.
const searchQuery = async () => {
const params = {
action: "query",
format: "json",
list: "search",
srsearch: "salvador dali",
};
const url = new URL("https://en.wikipedia.org/w/api.php/");
for (let param in params) {
url.searchParams.append(param, params[param]);
}
const searchData = await fetch(url);
console.log(searchData);
const data = await searchData.json();
console.log(data);
};

This is a CORS issue. To get around this, make the request from the server side or use a service like CORS Anywhere.
const url = new URL("https://corsanywhere.herokuapp.com/https://en.wikipedia.org/w/api.php/");

Related

I'm Receiving an error of failed to fetch when trying to fetch data from a recipe api. how can I fix this issue?

I'm trying to make a fetch request to a recipe API but am receiving this error and have no idea how to fix it
TypeError: Failed to fetch
Locally the request works fine, however now I've uploaded my application to netlify I've had this issue.
The code for my request is as follows
const API_KEY = process.env.REACT_APP_EDAMAM_API_KEY;
const APP_ID = process.env.REACT_APP_EDAMAM_APP_ID;
const url = `https://api.edamam.com/search?app_id=${APP_ID}&app_key=${API_KEY}&q=`;
const fetchMyApi = async (searchQuery) => {
try {
const response = await fetch(url + searchQuery);
const data = await response.json();
return data.hits;
} catch (err) {
console.log(err);
}
return [];
};
export default fetchMyApi;
I have no idea how to fix this issue.

Spotify API getting the error "No token provided" when fetching an endpoint

I am generating an access token every time the user tries to search a song with the spotify API beceuse I have seen that those token has an expiration time of 1h...
With the new access token I call the search endpoint but I get this response:
Object {
"error": Object {
"message": "No token provided",
"status": 401,
},
}
I don't have any idea why is that possible if I am passing the token to my GET request.
Here is the code:
export const searchMusic = async (query) => {
// Get an access token
const accessToken = await generateAccessToken();
console.log(accessToken); // <---- This shows the access token "BQAM...YualK"
// Request parameters
const params = {
q: query,
type: "track,album",
};
// Request url
const url = `https://api.spotify.com/v1/search${qs.stringify(params, {
addQueryPrefix: true,
})}`;
const response = await fetch(url, {
method: "GET",
header: {
Authorization: "Bearer " + accessToken, // <------- I pass the token as you can see here
},
});
const data = await response.json();
console.log(data); <----- Here comes the error
};
Does anybody knows what am I doing wrong? Also, is it bad to generate a new token everytime I try to fetch an endpoint? I mean, should I refresh it instead?
Thank you, I will really appreciate any guides.
For me, the problem was that I was using the api in the client, and my requirements needed to be run on the server... So, I moved my code to the server and all worked fine!
Maybe your API key isn't valid or doesn't give access to query that...
Code reference : https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401

How to make a fetch request with custom herokuapp proxy?

I'm trying to make a fetch request with custom herokuapp proxy to an API, but when I do that it gives an error. Error says "There is no Target-Endpoint header in the request". Here is my code.
var userTargetUrl = `http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=${steamApiKey}&vanityurl=${url}`
const response = await fetch(proxyUrl + userTargetUrl, {
headers: {
'Target-Endpoint': 'http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?'
}
})
const data = await response.json()
url = data['response']['steamid']
I'm following their instructions, but I couldn't figure it how to do it.
I won't pretend to be entirely sure, but maybe you can try
const response = await fetch(proxyUrl, {
headers: {
"Target-Endpoint": userTargetUrl
}
});

Append a query param to a GET request?

I'm trying to make a simple API that calls another API that will return some information. The thing is, in order to connect to the second API, I need to attach query parameters to it.
So what I've tried to do so far is to use an axios.get in order to fetch the API. If I didn't need to add queries on top of that, then this would be really simple but I'm having a really hard time trying to figure out how to attach queries on top of my request.
I've created an object that pulled the original query from my end and then I used JSON.stringify in order to turn the object I made into a JSON. Then, from my understanding of Axios, you can attach params my separating the URL with a comma.
On line 6, I wasn't sure if variables would carry over but I definitely can't have the tag var turned into the string "tag", so that's why I left it with the curly brackets and the back ticks. If that's wrong, then please correct me as to how to do it properly.
the var tag is the name of the query that I extracted from my end. That tag is what needs to be transferred over to the Axios GET request.
app.get('/api/posts', async (req, res) => {
try {
const url = 'https://myurl.com/blah/blah';
let tag = req.query.tag;
objParam = {
tag: `${tag}`
};
jsonParam = JSON.stringify(objParam);
let response = await axios.get(url, jsonParam);
res.json(response);
} catch (err) {
res.send(err);
}
});
response is SUPPOSED to equal a JSON file that I'm making the request to.
What I'm actually getting is a Error 400, which makes me think that somehow, the URL that Axios is getting along with the params aren't lining up. (Is there a way to check where the Axios request is going to? If I could see what the actual url that axios is firing off too, then it could help me fix my problem)
Ideally, this is the flow that I want to achieve. Something is wrong with it but I'm not quite sure where the error is.
-> I make a request to MY api, using the query "science" for example
-> Through my API, Axios makes a GET request to:
https://myurl.com/blah/blah?tag=science
-> I get a response with the JSON from the GET request
-> my API displays the JSON file
After looking at Axios' README, it looks like the second argument needs the key params. You can try:
app.get('/api/posts', async (req, res, next) => {
try {
const url = 'https://myurl.com/blah/blah';
const options = {
params: { tag: req.query.tag }
};
const response = await axios.get(url, options);
res.json(response.data);
} catch (err) {
// Be sure to call next() if you aren't handling the error.
next(err);
}
});
If the above method does not work, you can look into query-string.
const querystring = require('query-string');
app.get('/api/posts', async (req, res, next) => {
try {
const url = 'https://myurl.com/blah/blah?' +
querystring.stringify({ tag: req.params.tag });
const response = await axios.get(url);
res.json(response.data);
} catch (err) {
next(err);
}
});
Responding to your comment, yes, you can combine multiple Axios responses. For example, if I am expecting an object literal to be my response.data, I can do:
const response1 = await axios.get(url1)
const response2 = await axios.get(url2)
const response3 = await axios.get(url3)
const combined = [
{ ...response1.data },
{ ...response2.data },
{ ...response3.data }
]

coinmarketcap api integration - 401 error - JavaScript

I am trying to integrate coinmarketcap api but cannot really get the data. I registered, got the API key, and wrote the following method to fetch the data:
let getPostsList = async () => {
const options = {
method: 'GET',
headers: {
'X-CMC_PRO_API_KEY': 'api-key-goes-here'
},
mode: 'no-cors'
};
try {
const response = await fetch(`https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest`, options);
const json = await response.body;
// console.log(json)
return json
} catch (err) {
console.log('Error: ', err)
}
};
All I get is 401 error, like this:
GET https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest
401
Any suggestions what I should fix? Docs says that 401 is likely connected to API key, but they say to provide it in the headers like the above...
From what I've tested after getting my own API key, the no-cors mode is problematic. You will need to use CORS, where https://cors-anywhere.herokuapp.com/ comes into handy.
Just send the request like this :
const options = {
method: 'GET',
headers: {
'X-CMC_PRO_API_KEY': 'api-key-goes-here'
},
};
try {
const response = await fetch(`https://cors-anywhere.herokuapp.com/https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest`, options);

Categories

Resources