In python I wrote some code that allows me to fetch data by sending the session cookies:
import requests
url = "https://fantasy.espn.com/apis/v3/games/ffl/seasons/2021/segments/0/leagues/1662510081?view=mRoster"
print(url)
r = requests.get(url,
cookies={'swid': '{A1cFeg47WrVdsREQZNAo}',
'espn_s2': 'AWDB51sqnG8dsc3wfdsffsd'})
d = r.json()
d
I wanted to implement this in javascript so I wrote:
let leagueId = 1662510081;
let endpoint = "mRoster";
let url =
"https://fantasy.espn.com/apis/v3/games/ffl/seasons/2021/segments/0/leagues/" +
leagueId +
"?view=" +
endpoint;
console.log(url);
let playerList = [];
fetch(url)
.then((response) => response.json())
.then((data) => {
console.log(data)
});
How can I implement the cookies in the fetch request? I tried set-cookies in the headers but that didn't end up working.
Because your question tags nodejs, I'm assuming you are using node-fetch;
Apparently, there isn't any explicit way to send cookies, except using the headers method. So, you can use this code.
let fetch = require('node-fetch'); // or import fetch from 'node-fetch';
let leagueId = 1662510081;
let endpoint = "mRoster";
let url =
"https://fantasy.espn.com/apis/v3/games/ffl/seasons/2021/segments/0/leagues/" +
leagueId +
"?view=" +
endpoint;
console.log(url);
let playerList = [];
fetch(url, {
headers: {
cookie: "test=test"
}
})
.then((response) => response.json())
.then((data) => {
console.log(data)
}); // node-fetch
Also, browser/vanillaJS method:
...
fetch(url, {
credentials: 'include'
})
.then((response) => response.json())
.then((data) => {
console.log(data)
}); // browser/vanillaJS
Related
I've seen several posts about this, so I apologize if it's a direct duplicate. The examples I've seen have the RN components built with classes. I'm using functions, and I'm new, so it's all very confusing.
const getFlights = async () => {
const token = await getAsyncData("token");
instance({
method: "get",
url: "/api/flights/",
headers: {
Authorization: `Token ${token}`,
},
})
.then(function (response) {
// console.log(response.data.results); // shows an array of JSON objects
return response.data.results; // I've also tried response.data.results.json()
})```
I just want the response returned as a variable that I can use to populate a FlatList component in RN.
const FlightListScreen = () => {
const [list, setList] = useState([]);
const flights = getFlights(); // currently returns as a promise object
Thank you for your help.
I think you have to store the response object directly to the json method. And then with that response you can store it to the variable
.then(response => { return response.json() })
.then(response => {
this.setState({
list: response
})
you are sending token without a bearer. Concrete your token with bearer like this
headers: {
Authorization: "Bearer " + token,
},
and another thing is your response class are not right this should be like this
.then((response) => response.json())
.then((responseJson) => {
API will Resopne here....
}
this is a complete example to call API with Token
fetch("/api/flights/", {
method: "GET",
headers: {
Authorization: "Bearer " + token,
},
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
setState(responseJson.VAlue);
})
.catch((error) => {
alert(error);
});
backend server API send me a number and i have to fetch it in a response in react front end. But i am not able to read it by using response.json() or response.body(). Can anyone help me how to read the response as a number for fetch repsonse.
let url = "API URl"
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
fetch(url + new URLSearchParams({selectedReportName: this.state.selectedRepor}), requestOptions)
.then( response => response.json())
.then(data =>{
console.log ("Data " + data)} )
let url = "API URl"
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
fetch(url + new URLSearchParams({selectedReportName: this.state.selectedRepor}), requestOptions)
.then( response => response.json())
.then(data =>{
console.log ("Data " + data)} )
.catch(err => console.log("err:", err));
Try the above-mentioned code, It'll give you an exact error if we're not getting 200 response from the server or something is not working.
I trying to get a download of a json file from an API.
To do that, I need to call 3 endpoints.
http://url.com/export
it returns a json: {"exportLoading":true,"file":"export-20190618-183316.json"}
After that I should call the second endpoint and check the status of this exportation:
http://url.com/export/status
it returns true or false (while server is processing, this endpoint returns true. When it returns false the file is done to make a download.)
So, if the status === false, I can call the last endpoint
http://url.com/download/file_name (I make this request passing the file name - returned from the first request - to download the file.
My question is, how can I check if the second endpoint returns false to make the last request and download the file?
I just did it until the second endpoint.
app.get('/export', function (req, res, next) {
global.fetch = fetch
global.Headers = fetch.Headers;
const headers = new Headers();
const username = 'user';
const password = 'pass';
const URL = 'http://url.com/export'
headers.set('Authorization', 'Basic ' + base64.encode(username + ":" + password));
fetch(URL, {
method: 'GET',
headers: headers,
})
.then(res => res.json())
.then(json => {
fetch("http://url.com/exportl/status", {
method: 'GET',
headers: headers,
}).then(result => ...)
})
.catch(function (error) {
console.log(error)
})
});
You could use a while loop that will call the endpoint until the condition is met:
app.get('/export', async function(req, res, next) {
global.fetch = fetch
global.Headers = fetch.Headers;
const headers = new Headers();
const username = 'user';
const password = 'pass';
const URL = 'http://url.com/export'
headers.set('Authorization', 'Basic ' + base64.encode(username + ":" + password));
fetch(URL, {
method: 'GET',
headers: headers,
}).then(r => r.json)
.then(data => {
// use data here
var status = false
while (!status) {
status = await checkStatus()
}
// third call
})
});
function checkStatus() {
return fetch("http://url.com/exportl/status", {
method: 'GET',
headers: headers,
}).then(r => r.json)
}
Note, I do not know the response from the status, you will have to change the code to accommodate the response.
Im trying to fetch subcategories from my mvc application with reference to the category id with async fetch
I already fetched the categories and its all working
but when i try to fetch the subcategories with a post request it doesn't work!
//SubCategories
const categoriesLiList = document.querySelectorAll('.btn');
const getSubCategories = async () => {
const liBtnClick = list => {
nodeListForEach(list, cur => {
cur.addEventListener('click', () => {
debugger;
let categoryId = cur.value;
console.log(categoryId);
const getSubCategoriesById = async (url = ``, data = {}) => {
const subsResult = await fetch(url, {
method: "POST",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Content-Type": "application/json"
},
redirect: "follow",
referrer: "no-referrer",
body: JSON.stringify(data)
});
const subsData = await subsResult.json();
const populateSubCategories = arr => {
arr.forEach(cur => {
const subCategoriesLi = `
<li>${cur.Name}</li>
`;
document.querySelector('#subcategories').insertAdjacentHTML('beforeend', subCategoriesLi);
});
};
populateSubCategories(subsData);
};
getSubCategoriesById(`/controllername/jsonresult/ID`, { ID: categoryId });
});
});
};
liBtnClick(categoriesLiList);
};
getSubCategories();
The result should be the data from the api but its not reading the ID param.
what should i change in my post request??
EDIT: I am such an idiot lol my api wasn't working correctly, so for future purposes always test your apis with postman :)
also, there's no need for a post request! just a normal fetch get reques:
await fetch(`/controllerName/JsonResult/${categoryId}`);
I am such an idiot lol
my api wasn't working correctly, so for future purposes always test your apis with postman :)
also, there's no need for a post request! just a normal fetch get reques:
await fetch(`/controllerName/JsonResult/${categoryId}`);
I'm trying to fetch a multiple page api and place the json within an array. I've set it up so it does the required number of fetches and is setting up the correct number of promises. I am getting 50+ different responses. However, when I try to map each of those responses, it only pulls the first set of data and pushes that repetitively to the array. What am I not doing correctly?
var data;
fetch(URL_ARTISTS3,{
method:'GET'
})
.then(response => response.json())
.then(json => {
data =json;
const apiPromises = [];
var pagesRequired = Math.ceil(json.setlists["#total"] / json.setlists["#itemsPerPage"]);
for (let i=pagesRequired; i>0;i--) {
var fetchurl = URL_ARTISTS3 + '?page = ' + i;
apiPromises.push(fetch(fetchurl, {
method: "GET",
body: json
}));
}
Promise.all(apiPromises)
.then(responses => {
var processedResponses = [];
responses.map(response => response.json()
.then(json => {
/****THIS LINE ADDS THE SAME JSON RESPONSE MULTIPLE TIMES*****/
processedResponses.push(json.setlists.setlist);
})
)
console.log('processedResponses: ', processedResponses)
});
I'm not sure it solves the problem, but one issue is that you are logging processedResponses before the promises are resolved.
You can simplify your code a lot by moving the response.json() call:
apiPromises.push(
fetch(fetchurl, {method: "GET", body: json})
.then(response => response.json())
.then(json => json.setlists.setlist);
);
// ...
Promise.all(apiPromises).then(processedResponses => console.log(processedResponses));