【问题标题】:How to send session cookies in a fetch request?如何在获取请求中发送会话 cookie?
【发布时间】:2021-10-24 07:51:19
【问题描述】:

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

如何在获取请求中实现 cookie?我在标头中尝试了 set-cookies,但没有成功。

【问题讨论】:

    标签: javascript node.js fetch session-cookies


    【解决方案1】:

    因为你的问题标签 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
    

    【讨论】:

    • 它似乎不起作用。我可以在 chrome 开发者工具中的哪里查看正在传输的内容?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 2015-09-20
    • 2015-02-11
    • 2015-10-23
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多