簡體   English   中英

Flask會話在Angular App的請求之間不持久

[英]Flask session not persisting between requests for Angular App

我有一個Angular應用,需要調用Flask服務器,該服務器使用會話存儲請求之間的信息。

我還有一個較舊的JS應用程序,該應用程序使用XMLHttpRequest調用了同一台服務器,而我將其替換為新的Angular應用程序。

問題在於,當舊應用發出請求時,會話cookie可以按預期運行,但是現在使用角度應用卻無法正常工作。

所有交互都通過localhost完成。 Flask服務器可從localhost:5000訪問,而Angular應用可從localhost:4200

舊應用正在執行以下請求:

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

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)
  }

}

和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 https://stackoverflow.com/a/18709356/3729797 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

問題在於,當我登錄時,它將信息推送到會話中,而當我再次發出請求時,我會檢查該信息是否在會話中,但不是。

我在StackOverflow上發現了許多其他相關問題:

  • 與多次設置secret_key有關,這不是我的問題。
  • 這篇文章討論了init中的靜態配置與動態配置,但我認為這與我的問題無關嗎? 告訴我我是否錯。
  • 這個另一個都遇到了麻煩,因為它們在cookie中的有效負載太大,似乎只允許4096bytes或更小。 但是我只在cookie中輸入了幾個字母的用戶名,所以我不認為這是我的問題。
  • 這一個 ,因為它與本地主機涉及我還以為是有關我的問題,但事實證明,這是因為OP是混合的請求127.0.0.1localhost和餅干分別由燒瓶顯然處理。 我在localhost上執行所有請求,所以我認為不相關。

我現在有點迷路,可能有些明顯的東西我很想念,但無法弄清楚,任何建議都值得贊賞

我通過添加來使其工作

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

在發回所有請求之前,先在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

顯然,在進行CORS時需要使用MDN上的一些良好信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM