React 的访问控制允许凭据问题
这是一个使用 React 创建登录系统的项目。但是当连接后端flask检查登录是否有效时,却出现了如下错误信息。希望有人能帮助我。我花了很多天试图解决这个问题并搜索每个相关的帖子,但仍然无法解决它:(
我正在使用 chrome 浏览器。 另外,我在 chrome 上安装了 Access-Control-Allow-Origin 插件。
错误消息
Access to fetch at 'http://localhost:5000/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.
前端代码(react)
fetch(domain+"/login", {
body: JSON.stringify(mydata),
credentials: "include",
headers: new Headers({
'Content-Type': 'application/json',
'Access-Control-Allow-Credentials': true
}),
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // *client, no-referrer
})
.then(response=>{
if(response.ok){
return response.json()
}
}
后端(flask)包含以下代码以允许跨源
app = Flask(__name__)
CORS(app, supports_credentials=True)
@app.route('/login', methods=['GET', 'POST'])
def login():
data = request.json
print(data)
result = {}
login_info = {
"code": -1,
"message": ""
}
if data:
username = data['username']
password = data['password']
cur = database.cursor(dictionary=True)
cur.execute(
"SELECT username, password, role FROM user WHERE username = %s AND password = %s AND disabled = 0;", (username, password))
# cur.execute("SELECT uid, displayname, rank, disabled FROM user WHERE username = %s AND password = %s;", (username, password,))
# cur.execute("SELECT uid, displayname, rank, disabled FROM user WHERE username = %s AND password = AES_ENCRYPT(%s, UNHEX(SHA2('encryption_key', )));", (username, password,))
account = cur.fetchone()
if account:
# modify_info(1, "Login successfully!")
login_info["code"] = 1
login_info["message"] = "Login successfully!"
account_str = json.dumps(account, cls=MyEncoder)
account_json = json.loads(account_str)
session["username"] = account_json["username"]
result["username"] = username
result["role"] = account_json["role"]
result["isLogin"] = 1
else:
# modify_info(0, "Login not successful")
login_info["code"] = 0
login_info["message"] = "Login not successful"
cur.close()
return jsonify({"code": login_info["code"], "data": result, "message": login_info["message"]})
Here is a project to create a login system using react. However when it connects to the back-end flask to check whether the login is valid or not, it shows the error message below. Hope someone can help me. I spent so many days trying to fix this and search every related post but still couldn't fix it :(
I'm using the chrome browser.
Also, I have installed the Access-Control-Allow-Origin plugin on chrome.
error message
Access to fetch at 'http://localhost:5000/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.
front-end code (react)
fetch(domain+"/login", {
body: JSON.stringify(mydata),
credentials: "include",
headers: new Headers({
'Content-Type': 'application/json',
'Access-Control-Allow-Credentials': true
}),
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // *client, no-referrer
})
.then(response=>{
if(response.ok){
return response.json()
}
}
back-end(flask) include below code to allow cross origin
app = Flask(__name__)
CORS(app, supports_credentials=True)
@app.route('/login', methods=['GET', 'POST'])
def login():
data = request.json
print(data)
result = {}
login_info = {
"code": -1,
"message": ""
}
if data:
username = data['username']
password = data['password']
cur = database.cursor(dictionary=True)
cur.execute(
"SELECT username, password, role FROM user WHERE username = %s AND password = %s AND disabled = 0;", (username, password))
# cur.execute("SELECT uid, displayname, rank, disabled FROM user WHERE username = %s AND password = %s;", (username, password,))
# cur.execute("SELECT uid, displayname, rank, disabled FROM user WHERE username = %s AND password = AES_ENCRYPT(%s, UNHEX(SHA2('encryption_key', )));", (username, password,))
account = cur.fetchone()
if account:
# modify_info(1, "Login successfully!")
login_info["code"] = 1
login_info["message"] = "Login successfully!"
account_str = json.dumps(account, cls=MyEncoder)
account_json = json.loads(account_str)
session["username"] = account_json["username"]
result["username"] = username
result["role"] = account_json["role"]
result["isLogin"] = 1
else:
# modify_info(0, "Login not successful")
login_info["code"] = 0
login_info["message"] = "Login not successful"
cur.close()
return jsonify({"code": login_info["code"], "data": result, "message": login_info["message"]})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在规范中,
Access-Control-Allow-Credentials: true
标头不允许与Access-Control-Allow-Origin: *
标头。但是,
*
是 Flask cors 中原始标头的默认值,您应该将其设置为特定值,例如:另外,这里是有关它的文档的链接: https://flask-cors.readthedocs.io/en/latest/api.html
<一href="https://i.sstatic.net/uosPx.jpg" rel="nofollow noreferrer">
更新
这似乎是cookie问题的
samesite
,这里是设置它的代码:In the specification, the
Access-Control-Allow-Credentials: true
header is not allowed to use withthe
Access-Control-Allow-Origin: *
header.However,
*
is the default value for the origin header in flask cors, you should set it to a specific value, for example:Also, here is link to the document about it: https://flask-cors.readthedocs.io/en/latest/api.html
Update
It seems like the
samesite
of the cookie problem, here's the code to set it: