我正在开发模式(端口4200)上使用Angular 5将数据发布到我的Flask API(端口5000)。
我已经设置了Angular的环境以将发布请求重定向到:
export const environment = {
production: false,
url: 'http://localhost:5000'
};
我主要的Angular服务:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from '../environments/environment';
login = (username, password) => new Promise((resolve, reject) => {
// Temporary user to send
const user = {
username,
password
};
// Post current user
this.http.post(environment.url + '/login', user, httpOptions)
.subscribe((res: any) => {
if (res.success === 'OK') {
// Logged in successfully
console.log('Logged in !');
// Create a user
this.currentUser = user;
resolve(res);
} else {
// An error occured ?
console.log('Error with the received data.');
}
});
})
我正在尝试使用以下代码从我的Flask应用中保存和访问Cookie:
from flask import Flask, url_for, request, render_template, make_response, jsonify, session, redirect, escape
from flask_cors import CORS, cross_origin
app = Flask(__name__)
app.secret_key = b'\xd0\xb6_\xdf!%\xe8\xffy\x93\xca\xe5\xd6\xcfT{'
CORS(app, supports_credentials = True)
# Only answers to GET by default
@app.route('/')
def index():
resp = make_response("Get request on '/' !")
resp.set_cookie('asasa', 'bbbb')
print(request.cookies.get('asasa'))
# This prints 'None' the first time and 'bbbb' the nest ones, so it works
return resp
@app.route('/login', methods=['POST'])
def login():
......
resp = make_response(jsonify({...}))
resp.set_cookie('uid', 'aaaaa')
print('Cookies dictionnary contains the following:')
print(str(request.cookies))
return resp
Cookies的字典将始终为空,即使我多次调用它也是如此。 Chrome浏览器的检查器看不到该cookie,即使它看到在flask服务器的直接获取请求(第一个路由)上设置的cookie。
我也想使用会话,但是我认为问题与cookie相同,我想这是一个CORS问题,但似乎无法使其正常工作。
我也尝试过按照建议在服务器端使用这些手工头文件: Cross-Domain Cookies How do I set response headers in Flask?
resp.headers['Access-Control-Allow-Origin'] = '*' #http://localhost:4200'
resp.headers['Access-Control-Allow-Credentials'] = 'true'
resp.headers['Access-Control-Allow-Methods'] = '*'
resp.headers['Access-Control-Allow-Headers'] = 'Content-Type, *'
我尝试按照以下建议在Chrome中添加“ --disable-web-security”选项: Disable same origin policy in Chrome
我也看到了这些: Python Flask set cookie for both example.com and www.example.com Solve Cross Origin Resource Sharing with Flask
由于我查看了许多相关的帖子,但是仍然没有任何效果,因此我在这里提出要求,以便有人可以提供帮助...
提前谢谢