How to make a fetch request with custom herokuapp proxy? - javascript

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
}
});

Related

Error when trying to fetch from wikipedia

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/");

Getting CORS Error when using fetch to get data

I am trying to access the API to get some data however i keep getting this CORS error. I have checked my code for any syntax errors but i can't find any. I have attached a picture of the error and my function which is supposed to get the data.
async function getData(){
const request = await fetch('https://api.igdb.com/v4/games', {
method: 'POST',
headers: {
'Client-ID': 'jglmao8u28qo1p9wltqne325i7xh3u',
'Authorization': 'Bearer 4xau27m6liukizor4z2l8mlb7vbpjk',
}
})
const response = await request.json();
console.log(response);
}
There is a great proxy out there used just for this - bypassing a CORS block. The source code is here: https://github.com/Rob--W/cors-anywhere, and you would use it like this:
https://cors-anywhere.herokuapp.com/https://api.igdb.com/v4/games
basically just adding the CORS-Anywhere URL before your actual image URL.
In your situation, it would be
async function getData(){
const request = await fetch('https://cors-anywhere.herokuapp.com/https://api.igdb.com/v4/games', {
method: 'POST',
headers: {
'Client-ID': 'jglmao8u28qo1p9wltqne325i7xh3u',
'Authorization': 'Bearer 4xau27m6liukizor4z2l8mlb7vbpjk',
}
})
const response = await request.json();
console.log(response);
}
If you get rate limited by that website, try https://circumvent-cors.herokuapp.com/, this is one that I have deployed from the GitHub source code, no modifications and I do not think it should rate limit you.
Cheers, and let me know if this works.

How to get content-type from the response headers with Fetch

I'm trying to access the returned content-type from my GET request so I can decide the kind of preview I want to like for html maybe pass through an iframe and for a PDF maybe some viewer. The problem is when I do console.log(response.headers) the object returned doesn't have content-type in it but when I check the networks tab the response headers has content-type:html/text. How can I get the content-type from the response headers?
this is how my GET request looks like
const getFile = async () => {
var requestOptions = {
method: "GET",
headers: context.client_header,
redirect: "follow",
};
let statusID = context.currentStatus.ApplicationID;
var response = await fetch(
process.env.REACT_APP_API_ENDPOINT +
"/services/getStatus?ApplicationID=" +
statusID,
requestOptions
);
console.log(response.headers);
if (response.ok) {
let fileHtml = await response.text();
setfileURL(fileHtml);
} else {
alert.show("Someting went wrong");
}
};
The Headers object isn't a great candidate for console.log() since it is not easily serialisable.
If you want to see everything in it, try breaking it down to its entries via spread syntax
console.log(...response.headers)
You'll probably find that you can in fact access what you want via
response.headers.get("content-type")
See Headers.get()

Bad Request when trying to get an access token

I'm trying to use the Nest Device API, however I am unable to get an Access Token as it throws
{
"error": "invalid_grant",
"error_description": "Bad Request"
}
I've downloaded my credentials.json from GCP and I open a new tab with the AUTH_URL below:
const credentials = require('../../../credentials.json');
const PROJECT_ID = <NEST DEVICE API PROJECT ID>;
const REDIRECT_URL = 'http://localhost:3000/connect/callback';
const AUTH_URL =
`https://nestservices.google.com/partnerconnections/${PROJECT_ID}/auth?` +
`redirect_uri=${REDIRECT_URL}&access_type=offline&prompt=consent&client_id=${credentials.web.client_id}&` +
`response_type=code&scope=https://www.googleapis.com/auth/sdm.service`;
From that, I have my callback page that gets the authcode.
const credentials = require('../../../credentials.json');
const { code } = router.query; // Auth Code
try {
const url =
`https://www.googleapis.com/oauth2/v4/token?client_id=${credentials.web.client_id}` +
`&client_secret=${credentials.web.client_secret}&code=${code}&grant_type=authorization_code&` +
`redirect_uri=${REDIRECT_URL}`;
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
});
console.log(response);
} catch (e) {
console.error(e);
}
This is where the API returns the above error. I have also tried taking this URL and doing curl -L -X POST <url> however I get exactly the same results.
Any ideas?

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