我有一个Angular应用程序,需要调用Flask服务器,该服务器使用会话在请求之间存储信息。
我还有一个旧的JS应用程序,它使用XMLHttpRequest调用同一个服务器,我正在用新的Angular应用程序替换它。
问题是,当旧应用程序发出请求时,会话cookie按预期工作,但现在使用angular应用程序时,情况并非如此。
所有交互都是通过本地主机完成的。可以从以下位置访问Flask服务器:
localhost:5000
,以及
localhost:4200
.
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:5000/api/getAll", true);
xhttp.withCredentials = true;
xhttp.send();
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
问题是,当我登录时,它会将信息推送到会话中,当我执行另一个请求时,我会检查该信息是否在会话中,但它没有。
-
this one
与多次设置密钥有关,这不是我的问题。
-
this one
-
this one
和
this other one
因为cookie中的40字节太大或太少,所以它们的有效负载看起来太大或太少。但我只在我的cookie中输入了几个字母的用户名,所以我不认为这是我的问题。
-
this one
我认为这与我的问题有关,因为它处理本地主机,但事实证明,这是因为OP在主机上混合了请求
127.0.0.1
和
localhost
本地服务器
所以我相信没有关系。
我现在有点迷路了,可能有一些很明显的东西我遗漏了,但我想不出来,任何建议都很感激