Flask Session Not Persisting (Postman works, Javascript doesn't)

前端 未结 2 1994
走了就别回头了
走了就别回头了 2021-02-09 17:28

I\'m developing a Flask server to communicate between some backend Python functionality and Javascript clients over the web. I\'m attempting to utilize Flask\'s session

2条回答
  •  说谎
    说谎 (楼主)
    2021-02-09 17:44

    After a few hours of testing, I managed to figure out the issue. Although I think @amanb's answer highlights the problem, I'm going to answer my own question because what I found is ultimately a simpler solution.

    In order to make the POST request return the expected value, I simply needed to add a credentials: 'same-origin' line to the fetch body. This looks like the following:

    var url = 'http://my_server_ip/update';
    fetch(url, {
      method: 'POST',
      body: JSON.stringify('arbitrary_string'),
      credentials: 'same-origin',   // this line has been added
      headers: {
        'Content-Type': 'application/json'
      }
    })
    .then(response => response.json())
    .then((data) => {
      console.log(data);
    })
    

    According to Mozilla's Fetch usage guide,

    By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session.

    So it seems I looked over this. Changing the credentials to allow communication of the cookie/session between client and server resolved the issue.

提交回复
热议问题