0

I wrote some code that does a get request in python 3.5 and it returns with a successful status code. Now, I want to convert it to javascript but i am getting a 401 unauthorized error.

Here is what my python code works like that is working:

import requests
import pprint

base = "http://fantasy.espn.com/apis/v3/games/ffl/seasons/"
year = "2019"
mid = "/segments/0/leagues/"
leagueId = "myLeagueId"
url = base + year + mid + leagueId
swid = "{mySWIDcookie}"
espn_s2 = "myEspn_s2cookie"


r = requests.get(url,
                 cookies={"SWID": swid,
                          "espn_s2": espn_s2 })


d = r.json()
pprint.pprint(d)

And here is what my JavaScript conversion looks like that returns unsuccessful.

const base = "http://fantasy.espn.com/apis/v3/games/ffl/seasons/";
const year = "2019";
const mid = "/segments/0/leagues/";
const leagueId = "myLeagueId";
const url = base + year + mid + leagueId;
const swid = "{mySWIDcookie}";
const espn_s2 = "myEspn_s2cookie";
let headers = new Headers();
headers.set("Set-Cookie", "SWID=swid; espn_s2=myEspn_s2cookie;");
var myInit = { method: "Get", headers: headers};
var request = new Request(url,myInit);
fetch(request).then(function(response) {
    return response.text();
}).then(function(text) {
    console.log(text);
})

Does anyone see what I'm doing wrong? Thanks.

Nizzy
  • 209
  • 3
  • 9
  • https://stackoverflow.com/questions/35588699/response-to-preflight-request-doesnt-pass-access-control-check maybe this will help.... – Pratik Gandhi Nov 10 '19 at 15:49

1 Answers1

0

Please check the docs of fetch, 1st parameter is the url, the second parameter is an object speficying the request options

Here is an example, hope it helps

// Default options are marked with *
      const response = await fetch(url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
          'Content-Type': 'application/json'
          // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrer: 'no-referrer', // no-referrer, *client
        body: JSON.stringify(data) // body data type must match "Content-Type" header
      });
      return await response.json(); // parses JSON response into native JavaScript objects
    }