I am trying to create a search page for Pathfinder. Below is the code I wrote to try and pull in the data from the api. While trying to just get the fetches to work, I am noticing when I console.log the data returned from the fetches, it is listed more than once.
async function getData(){
const apiKey = "API KEY WITHHELD";
const actionsURL = "https://api.pathfinder2.fr/v1/pf2/action";
const ancestriesURL = "https://api.pathfinder2.fr/v1/pf2/ancestry";
const ancestryFeaturesURL = "https://api.pathfinder2.fr/v1/pf2/ancestryFeature";
const archetypesURL = "https://api.pathfinder2.fr/v1/pf2/archetype";
const backgroundsURL = "https://api.pathfinder2.fr/v1/pf2/background";
const classesURL = "https://api.pathfinder2.fr/v1/pf2/class";
const classFeaturesURL = "https://api.pathfinder2.fr/v1/pf2/classFeature";
const deitiesURL = "https://api.pathfinder2.fr/v1/pf2/deity";
const equipmentURL = "https://api.pathfinder2.fr/v1/pf2/equipment";
const featsURL = "https://api.pathfinder2.fr/v1/pf2/feat";
const spellsURL = "https://api.pathfinder2.fr/v1/pf2/spell";
// Actions
const actionsResponse = await fetch(actionsURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const actionsData = await actionsResponse.json();
// Ancestries
const ancestriesResponse = await fetch(ancestriesURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const ancestriesData = await ancestriesResponse.json();
// Ancestry Features
const ancestryFeaturesResponse = await fetch(ancestryFeaturesURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const ancestryFeaturesData = await ancestryFeaturesResponse.json();
// Archetypes
const archetypesResponse = await fetch(archetypesURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const archetypesData = await archetypesResponse.json();
// Backgrounds
const backgroundsResponse = await fetch(backgroundsURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const backgroundsData = await backgroundsResponse.json();
// Classes
const classesResponse = await fetch(classesURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const classesData = await classesResponse.json();
// Class Features
const classFeaturesResponse = await fetch(classFeaturesURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const classFeaturesData = await classFeaturesResponse.json();
// Deities
const deitiesResponse = await fetch(deitiesURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const deitiesData = await deitiesResponse.json();
// Equipment
const equipmentResponse = await fetch(equipmentURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const equipmentData = await equipmentResponse.json();
// Feats
const featsResponse = await fetch(featsURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const featsData = await featsResponse.json();
// Spells
const spellsResponse = await fetch(spellsURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Access-Control-Allow-Headers": "*",
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const spellsData = await spellsResponse.json();
// do what you want with actionsData and ancestriesData, etc here
console.log(actionsData);
console.log(ancestriesData);
console.log(ancestryFeaturesData);
console.log(archetypesData);
console.log(backgroundsData);
console.log(classesData);
console.log(classFeaturesData);
console.log(deitiesData);
console.log(equipmentData);
console.log(featsData);
//console.log(spellsData);
}
getData();
Originally I used a fetch to grab all of the endpoints listed in the main endpoint (see page: https://api.pathfinder2.fr/doc) and then ran a loop to fetch data from each endpoint -- DRY principles and what not.
const apiKey = "API KEY WITHHELD";
let pathfinderLibraries = [];
let pathfinder = fetch("https://api.pathfinder2.fr/v1/pf2", {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": "application/json",
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
}).then((response) => {
return response.json()
})
.then(data => {
let pflibraries = data;
//console.log(pflibraries);
pflibraries.forEach(pflibrary => {
pathfinderLibraries.push(pflibrary);
pathfinderLibraries.forEach( library => {
fetch(library, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": "application/json",
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
}).then((response) => {
return response.json()
}).then(data => {
console.log(data);
});
});
console.log(pflibrary);
});
});
But this was logging each of the endpoint data multiple times so I decided to try it without the loop. This decreased the amount of times each endpoint data was logged, but the data was still being logged multiple times.
I experimented with changing the location of the console.logs and had 1 of 2 results, either it did not log at all or continued to log multiple times.
As I said previously, I just wanted to create a function with a loop that would iterate through main endpoint that lists the sub-endpoints and fetch the data so I can create a search page for Pathfinder.
In this block of code
pflibraries.forEach(pflibrary => {
pathfinderLibraries.push(pflibrary);
pathfinderLibraries.forEach( library => {
you traverse through pflibraries and each of them you are adding into pathfinderLibraries. Right after that you traverse through pathfinderLibraries.
This means that after every loop through pflibraries your list of libraries in pathfinderLibraries will contain pflibrary from the current iteration and also from all the previous iterations of pflibraries.
To fix the problem you need to remove this forEach from the code
pathfinderLibraries.forEach( library => {
and just call the fetch for the library in the current iteration.
Related
I´m refering to this post: Fetch: POST JSON data
I´ve copied the code which is linked down below.
My question is, is it possible to save for example "Content-Length" which i get as a response in the JSON-file as a variable with which i can continue to work?
Looking forward!
Thanks already!
fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 7, str: 'Some string: &=&'})
}).then(res => res.text())
.then(res => console.log(res));
And my result is:
{
"args": {},
"data": "{\"a\":7,\"str\":\"Some string: &=&\"}",
"files": {},
"form": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Accept-Encoding": "br, gzip, deflate",
"Accept-Language": "*",
"Content-Length": "32",
"Content-Type": "application/json",
"Host": "httpbin.org",
"Sec-Fetch-Mode": "cors",
"User-Agent": "undici",
"X-Amzn-Trace-Id": "Root=1-6388fb1d-3f7791960bdce04f36356182"
},
"json": {
"a": 7,
"str": "Some string: &=&"
},
"origin": "79.208.157.109",
"url": "https://httpbin.org/post"
}
Of course you can - just access it and store it in a variable:
const example = async() => {
const res = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 7, str: 'Some string: &=&'})
})
const response = await res.json()
const contentLength = response.headers['Content-Length'];
displayContentLength(contentLength);
}
function displayContentLength(length) {
console.log('The content length is: ' + length);
}
example();
I am working on implementation of strava in my website. I am new to JavaScript and I am not understanding whether I am doing it correctly or not. My problem is I am unable to get access token from JSON response. I don't know why. Please Help me.
the resonse what I am getting
code
<script>
const auth_link = "https://www.strava.com/oauth/token"
function getActivites(res){
console.log('response2',res.json());
const activities_link = `https://www.strava.com/api/v3/athlete/activities?access_token=${res.access_token}`
fetch(activities_link)
.then((res) => console.log(res.json()))
}
function reAuthorize(){
fetch(auth_link,{
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({
client_id: 'xxxx',
client_secret: 'xxxxx',
refresh_token: 'xxxxx',
grant_type: 'refresh_token'
})
})
.then(res => {
var response = res.json();
var access_token = response.access_token;
console.log('response',access_token)
// getActivites(res)
})
}
reAuthorize()
</script>
I am getting access token as undefined
function reAuthorize() {
fetch(auth_link, {
method: "post",
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json"
},
body: JSON.stringify({
client_id: "55077",
client_secret: "801a8541e8ae55cffee584a48c5bb6a233dea9a0",
refresh_token: "08342cdf3250da9e0d1b53303fa40faf0d05965d",
grant_type: "refresh_token"
})
}).then(response => response.json())
.then(data => console.log(data));
}
I am new to front end dev. How can I set "application/json" content-type and gzip content-encoding in the fetch call in locally run React code?
const data = await fetch(url, {
method: 'post',
body: body,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json' // this does not work when run locally
}
});
You could try this
const data = await fetch(url, {
method: 'post',
body: JSON.stringify(body), // this will encode body to string, assuming it's an Object
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
but I'm not sure what do you want with "gzip content-encoding". If the console prints any errors, they can be helpful too
I’ve this axios request which is running ok I got http 200
import {AxiosResponse} from "axios";
const axios = require('axios').default;
const qs = require('qs');
//First query
axios({
method: 'post',
url: 'https://oauth2.-arch.mand.com/oauth2/token',
data: qs.stringify({'grant_type': 'client_credentials'}, {'scope': 'run:crud'}),
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
'Content-Type': 'application/x-www-form-urlencoded',
}
}).then(function (response: AxiosResponse) {
console.log(response.data);
}).catch(function (error: any) {
console.log("Error: " + error);
});
//Second query (the only different is the scope )
axios({
method: 'post',
url: 'https://oauth2.-arch.mand.com/oauth2/token',
data: qs.stringify({'grant_type': 'client_credentials'}, {'scope': ‘exe:crud’}),
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
'Content-Type': 'application/x-www-form-urlencoded',
}
}).then(function (response: AxiosResponse) {
console.log(response.data);
}).catch(function (error: any) {
console.log("Error: " + error);
});
Now I want to run two request in parallel and get the results which is response.data (the data I sent to the request / headers etc)
I’ve tried with but the response I got is like the request , I don’t get the tokens/data? Any idea
How can I use this two request in parallel ?
axios.all([{
method: 'post',
url: 'https://oauth2.-arch.mand.com/oauth2/token',
data: qs.stringify({'grant_type': 'client_credentials'}, {'scope': 'run:crud'}),
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
'Content-Type': 'application/x-www-form-urlencoded',
}
},
{
method: 'post',
url: 'https://oauth2.-arch.mand.com/oauth2/token',
data: qs.stringify({'grant_type': 'client_credentials'}, {'scope': 'exe:crud'}),
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
'Content-Type': 'application/x-www-form-urlencoded',
}
}]).then(axios.spread((...responses: AxiosResponse[]) =>{
const aToken = responses[0];
const bToken = responses[1];
}).catch(function (error: any) {
console.log("Error: " + error);
});
If there is a better way , please let me know
Btw, if I run this two post request separated everything is working fine
You need to provide promises to the axios.all not their config objects.
axios.all([
axios({
method: 'post',
url: 'https://oauth2.-arch.mand.com/oauth2/token',
data: qs.stringify({
'grant_type': 'client_credentials'
}, {
'scope': 'run:crud'
}),
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
'Content-Type': 'application/x-www-form-urlencoded',
}
}),
axios({
method: 'post',
url: 'https://oauth2.-arch.mand.com/oauth2/token',
data: qs.stringify({
'grant_type': 'client_credentials'
}, {
'scope': 'exe:crud'
}),
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
'Content-Type': 'application/x-www-form-urlencoded',
}
})
]).then(axios.spread((...responses: AxiosResponse[]) => {
const aToken = responses[0];
const bToken = responses[1];
}).catch(function(error: any) {
console.log("Error: " + error);
});
Keep in mind though that the axios.all and axios.spread are deprecated.
Use Promise.all directly
how to handle request header accept application/ld+json in react.js get request
Media type
application/id+json
Controls Accept header.
i am getting unauthorized 401 error dont know why can anyone please explain me i am facing this type of error for the first time .
function parseJwt(token) {
if (!token) { return; }
const base64Url = token.split('.')[1];
const base64 = base64Url.replace('-', '+').replace('_', '/');
return JSON.parse(window.atob(base64));
}
export async function getRequest(url , token){
let token_data = parseJwt(token)
console.log('Token data ', token_data)
let response = await fetch(API_URL(url), {
method: "GET",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Accept": `application/${token_data.id}+json`,
// 'Content-Type': `application/${token_data.id}+json`,
// "Authorization": JSON.stringify(token_data)
},
redirect: "follow",
referrer: "no-referrer",
})
return response
}
Please Try Below code
var token = 'XXXXX-XXXX-XXXXX';
const response = await fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': token
},
body: payLoad,
})