我在python中编写了一些代码,允许我通过发送会话cookie来获取数据:
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
我想在javascript中实现这个,所以我写:
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)
});
如何在fetch请求中实现cookie ?我试过在标题中设置cookie,但最终没有工作。
因为你的问题标签nodejs,我假设你使用的是node-fetch
;
显然,除了使用headers
方法外,没有任何显式的方式发送cookie。因此,您可以使用此代码。
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
同样,browser/vanillaJS
法:
...
fetch(url, {
credentials: 'include'
})
.then((response) => response.json())
.then((data) => {
console.log(data)
}); // browser/vanillaJS