Flask 会话不会在 Angular App 的请求之间持续存在

Jul*_*usé 6 python session flask angular

我有一个 Angular 应用程序,它需要调用一个 Flask 服务器,该服务器使用会话在请求之间存储信息。

我还有一个旧的 JS 应用程序,它使用 XMLHttpRequest 调用同一个服务器,我正在用新的 Angular 应用程序替换它。

问题在于,当旧应用程序发出请求时,会话 cookie 会按预期工作,但现在使用 angular 应用程序时却没有。

所有交互都通过本地主机完成。Flask 服务器可从 访问localhost:5000,Angular 应用程序可从localhost:4200.

旧应用程序正在执行这样的请求:

var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:5000/api/getAll", true);
xhttp.withCredentials = true;
xhttp.send();
Run Code Online (Sandbox Code Playgroud)

Angular 应用程序是这样做的:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, } from '@angular/common/http';
import { Observable } from 'rxjs';

const httpOptions = {
  withCredentials: true,
  headers: new HttpHeaders({ 
    'Content-Type': 'application/json',
    'charset': 'UTF-8',

    })
};


@Injectable()
export class ServerService {
  url = "http://localhost:5000/api/"

  constructor(private http:HttpClient) { }

  getAll(): Observable<string>{
    return this.http.get<string>(this.url + 'getAll', httpOptions);
  }

  login (username: string): Observable<string> {
    return this.http.post<string>(this.url + 'login', JSON.stringify({"username": username}), httpOptions)
  }

}
Run Code Online (Sandbox Code Playgroud)

和 Flask 服务器:

from flask import Flask, session, request, jsonify
from flask_cors import CORS
import os
import Person
import multiprocessing as mp
import json
import Insurance
import datetime
import Functions
import missingVal


app = Flask(__name__)
CORS(app, supports_credentials=True)

# set the secret key. keep this really secret:
# The value come from calling os.urandom(24)
# See /sf/answers/1309654951/ for more information
# app.secret_key = b'fL\xabV\x85\x11\x90\x81\x84\xe0\xa7\xf1\xc7\xd5\xf6\xec\x8f\xd1\xc0\xa4\xee)z\xf0'
app.config['SECRET_KEY'] = b'fL\xabV\x85\x11\x90\x81\x84\xe0\xa7\xf1\xc7\xd5\xf6\xec\x8f\xd1\xc0\xa4\xee)z\xf0'




@app.route('/api/getAll')
def getAll():
    response = jsonify()
    if 'username' in session:
        user = users[session['username']]
        # some more logic here
        response = jsonify({'username': session['username']})

    return response

# login and account creation    
@app.route('/api/login', methods=['POST'])
def login():
    response = jsonify()
    if users.get(request.json.get('username')) is not None:
        session['username'] = request.json.get('username')
        # some more logic here
        response = jsonify({'username': session['username']})

    response.headers.add('Access-Control-Allow-Methods',
                         'GET, POST, OPTIONS, PUT, PATCH, DELETE')
    response.headers.add('Access-Control-Allow-Headers',
                         "Origin, X-Requested-With, Content-Type, Accept, x-auth")
    return response


if __name__ == '__main__':
    # some more logic here
    app.run(host='localhost', threaded=True
Run Code Online (Sandbox Code Playgroud)

问题是,当我登录时,它会将信息推送到会话中,而当我执行另一个请求时,我会检查该信息是否在会话中,但没有。

我在 StackOverflow 上发现了很多其他相关问题:

  • 与多次设置secret_key有关,这不是我的问题。
  • 这个讨论了 init 中的静态与动态配置,但我认为这与我的问题无关?告诉我如果我错了。
  • 这个另一个有问题,因为它们在 cookie 中的有效载荷太大,似乎只允许 4096 字节或更少。但是我只在我的 cookie 中输入了一个只有几个字母的用户名,所以我不相信这是我的问题。
  • 这个我认为与我的问题有关,因为它处理本地主机,但事实证明这是因为 OP 正在混合请求127.0.0.1localhost并且 cookie 显然是由烧瓶单独处理的。我做我所有的请求,localhost所以我相信不相关。

我现在有点迷茫,可能有一些很明显的东西我遗漏了但无法弄清楚,任何建议表示赞赏

Jul*_*usé 4

我通过添加让它工作

response.headers.add('Access-Control-Allow-Headers',
                         "Origin, X-Requested-With, Content-Type, Accept, x-auth")
Run Code Online (Sandbox Code Playgroud)

在发回所有请求之前在 Flask 服务器中。

例如

@app.route('/api/doSomething', methods=['POST'])
def doSomething():
    response = jsonify()
    if 'username' in session:
        # some logic here
        response = jsonify(someData)

    # here is the line I added
    response.headers.add('Access-Control-Allow-Headers',
                         "Origin, X-Requested-With, Content-Type, Accept, x-auth")
    return response
Run Code Online (Sandbox Code Playgroud)

显然是做CORS的时候需要的,MDN上有一些不错的资料