gpt4 book ai didi

python - Flask session 不会在 Angular App 请求之间持续存在

转载 作者:太空宇宙 更新时间:2023-11-04 02:12:52 27 4
gpt4 key购买 nike

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

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

问题在于,当旧应用程序发出请求时, session 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();

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

问题是,当我登录时,它会将信息推送到 session 中,而当我发出另一个请求时,我会检查该信息是否在 session 中,但事实并非如此。

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

  • this one与多次设置 secret_key 有关,这不是我的问题。
  • this one谈论 init 中的静态配置与动态配置,但我认为这与我的问题无关?如果我错了,请告诉我。
  • this onethis other one遇到了麻烦,因为他们在 cookie 中的有效负载太大,似乎只允许 4096 字节或更少。但我只将几个字母的用户名放入我的 cookie,所以我不认为这是我的问题。
  • this one我认为与我的问题有关,因为它处理本地主机,但事实证明这是因为 OP 在 127.0.0.1localhost 上混合请求,cookie 是单独处理的显然是 flask 。我在 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 的好信息

关于python - Flask session 不会在 Angular App 请求之间持续存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53341497/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com