IGDB API Axios request returning undefined - javascript

I building a Discord bot, and I want to query IGDB for the searched game and return some information. I'm currently just getting 'undefined' no matter what I search or change.
I'm using CORS-anywhere as a proxy. Not sure if that's the issue. How can I get the response to show data in the console like it does in Postman?
Here's my code:
client.on('message', (message) => {
if (message.author.bot) return;
if (message.content.startsWith(PREFIX)) {
const [CMD_NAME, ...args] = message.content
.trim()
.substring(PREFIX.length)
.split(/\s+/);
if (CMD_NAME === 'search') {
if (args.length === 0) return message.reply('Please provide a game.');
// Perform a GET request from the IGDB API through the cors-anywhere proxy.
const proxyUrl = 'https://cors-anywhere.herokuapp.com/'
axios({
url: `${proxyUrl}https://api-v3.igdb.com/games`,
method: 'POST',
headers: {
'Origin': 'https://api-v3.igdb.com/games',
'Accept': 'application/json',
'user-key': process.env.IGDB_USER_KEY
},
data: `fields name,first_release_date,platforms,cover,summary;search ${args};sort popularity desc;limit 1;`
})
.then(response => {
console.log(response.data);
})
.catch(err => {
console.log(err.response.request._response);
})
}
}
})```

I am also working on igdb and pretty new with it. If I'm wrong let me know and i'll remove this :D
I think the headers should be different now that twitch auth is required.
You must call https://id.twitch.tv/oauth2/token? in order for you to get a access_token that you can then pass in your request's headers together with your client_id.
Now that you have a Client ID and Client Secret you will be
authenticating as a Twitch Developer using oauth2. Detailed
information can be found on the Twitch Developer Docs.
Doing so will give you an access token that is used for future
requests to our API.
Make a POST request to https://id.twitch.tv/oauth2/token with the
following query string parameters, substituting your Client ID and
Client Secret accordingly.
client_id=Client ID
client_secret=Client Secret
grant_type=client_credentials
headers: {
'Accept': 'application/json',
'Client-ID':'your_client_id',
'Authorization':'Bearer access_token'
},
https://api-docs.igdb.com/?javascript#about

Related

Fetch API call not fetching cookies in expo react native?

I'm trying to send a post request to the server but the response does not contain 'set-cookie' header but the cookie is visible in postman.
This is the code:
axios.defaults.withCredentials = true;
let config = {
method: 'post',
url: 'https://app.bhive.fund/v1/api/account/signin',
headers: {
'Content-Type': 'application/json',
},
data: form
}
const res = await axios(config)
console.log(res.status)
console.log('set-cookie: ');
console.log(res.headers['set-cookie']);
console.log(res.headers);
return res;
This is the screenshot of the log
This is the screenshot of postman
That's because of the res.headers can't be accessed like an object.
You have to use the get()-method specified in order to get the cookie.
Try this instead of accessing the value right away by specifying the index with the brackets:
console.log(res.headers.get("Set-Cookie"));

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.

Why do i get "Must provide query string" on fetch API but not on cURL or Postman?

I am trying to use the graphbrainz library on a React app with fetch API, but however I format my request body, this error shows:
BadRequestError: Must provide query string. at graphqlMiddleware (C:\Users\User\Desktop\project\node_modules\express-graphql\index.js:76:44) at processTicksAndRejections (internal/process/task_queues.js:95:5)
The call is being made like this:
let myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
const raw = "{ \"query\": \"{ lookup { releaseGroup(mbid: \\\"99599db8-0e36-4a93-b0e8-350e9d7502a9\\\") { title } }}\"}";
const requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow',
mode: 'no-cors'
};
fetch("http://localhost:3000", requestOptions)
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log('error', error));
I have tried making the same call on Postman and cURL and it works successfully.
The graphbrainz instance is being run as a standalone node server.
Can anyone guide me how to proceed with this or what am I doing wrong? I have exhausted almost all stackoverflow questions and GitHub threads. I have the idea that it must be the bodyParser on the express-graphql server that it is causing this, but I can't see how to change/modify it since it comes from the package I am using.
I think you might be escaping inner quotes in the query incorrectly. Try replacing \"99599db8-0e36-4a93-b0e8-350e9d7502a9\" with \\\"99599db8-0e36-4a93-b0e8-350e9d7502a9\\\".
Can you try to stringify your body payload before sending it.
const raw = JSON.stringify({
"query": "{ lookup { releaseGroup(mbid: \"99599db8-0e36-4a93-b0e8-350e9d7502a9\") { title } }}"
});
doing this will stringify your payload to
"{\"query\":\"{ lookup { releaseGroup(mbid: \\\"99599db8-0e36-4a93-b0e8-350e9d7502a9\\\") { title } }}\"}"

Getting 401 error when using redmine API for a POST request even though I have included the api key

I am trying to make a post request to create a new wiki page using the redmine-api. I am using JavaScript and Axios. However I a getting a 401 error(UnAuthorize).
My goal is to be able to send a word document to my redmine and create a wiki page.
I am using the Api key provided and I did enable the rest api feature in my redmine setting
I have included the api key in the header however it is not working.
var wordDocument = "./Redmine.docx"
axios.post('<website url>/uploads.json', {
headers: {
'Content-Type': 'application/octet-stream',
'Cache-Control': 'no-store',
'key': '<api-key>'
},
data:wordDocument
})
.then(function (response) {
console.log("succeeed---> ");
console.log (response)
})
.catch(function (error) {
console.log("failed-----> ");
console.log(error.response.headers)
console.log(error.message)
console.log("failed-----> ");
})
I am getting a status: '401 Unauthorized',
Try using the other authentication methods mentioned in the docs:
x passed in as a "key" parameter
- passed in as a username with a random password via HTTP Basic authentication
- passed in as a "X-Redmine-API-Key" HTTP header (added in Redmine 1.1.0)
https://www.redmine.org/projects/redmine/wiki/Rest_api#Authentication
Also ensure that you're using the correct API key.
You can find your API key on your account page ( /my/account ) when logged in, on the right-hand pane of the default layout.
Alright I got it working.
I did "axios({})" instead of "axios.post". I do not know what the different is? I thought it was the same.
Here is my code for anyone who run into this.\
var wordDocument = "./Redmine.docx"
axios({
method: 'post',
url: '<redmind_url>/uploads.json',
headers: { 'Content-Type': 'application/octet-stream'},
params: { 'key': '<api key>'},
data: wordDocument
})
.then(function (response) {
console.log("succeeed---> ");
console.log(response.data)
})
.catch(function (error) {
console.log("failed-----> ");
console.log(error.response.statusText, "-->", error.response.status);
console.log(error.response.headers)
console.log(error.message)
console.log("failed-----> ");
})

Yelp API Authorization using JavaScript

I am still learning to work with different APIs, and have been working with JavaScript and the Yelp API. I have tried using Ajax, as well as the code I have posted here, but I continue to get the error of:
"code": "TOKEN_MISSING",
"description": "An access token must be supplied in order to use this endpoint."
I will continue to search through other posts, but if anyone could point out to me what I am doing incorrectly and how to fix it, I would really appreciate it?
var URL = 'https://api.yelp.com/v3/businesses/search?location=40515&term&categories=vet&limit=10';
var API_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxx';
var req = new Request(url, {
method: 'GET',
headers: new Headers({
'Authorization: Bearer', API_KEY,
'Content-Type': 'application/json'
})
mode: 'no-cors'
});
fetch (req)
.then((response) => {
if(response.ok){
return response.json();
}else{ssss
throw new Error();
}
})
.then((jsonData) => {
console.log(jsonData);
})
.catch((err) => {
console.log('ERROR: ', err.message);
});
I think you just need to fix up:
'Authorization: Bearer', API_KEY,
to be something like:
'Authorization': `Bearer ${API_KEY}`,
or:
'Authorization': 'Bearer ' + API_KEY,
And if this line isn't just redacted for posting here:
var API_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxx';
then you would need to actually get an API key from yelp as 'xxxxxxxxxxxxxxxxxxxxxxxxxx' would not be a valid key
I think an answer I posted before to a similar question with a full code sample may lead you in the right direction:
https://stackoverflow.com/a/51461033/9525657
Have a look, it’s an easy and simple process of pulling from the service :)

Categories

Resources