我正在用Flask&反应,尽管使用烧瓶CORS所有默认值不变(允许所有标头和原点(请求来自React被Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/auth/check_passport. (Reason: CORS request did not succeed).
拒绝
烧瓶:
from flask_cors import CORS
def create_app(script_info=None):
app = Flask(__name__)
app.config.from_object(current_config)
from project.api.auth import auth_blueprint
app.register_blueprint(auth_blueprint)
CORS(app)
return app
在航站楼里,我可以看到它到达了Flask:127.0.0.1 - - [20/Apr/2021 10:36:59] "POST /auth/check_passport HTTP/1.1" 200
根据文档,将CORS保留为默认值允许任何客户端到达端点。
非常感谢您的反馈。
编辑:
auth.py:
from flask import Blueprint, request
auth_blueprint = Blueprint('auth', __name__, url_prefix='/auth')
@auth_blueprint.route('/check_passport', methods=['POST'])
def check_passport():
print('called') # isn't being printed out
image_received = request.data['image']
...
...
前端:
const checkPassport = () => {
if (passportFile) {
const fd = new FormData();
fd.append("image", passportFile, passportFile.name);
const url = "http://localhost:5000/auth/check_passport";
const config = {
headers: {
"Content-Type": "multipart/form-data"
}
};
axios
.post(url, fd, config)
.then(resp => {
console.log(resp.data.message);
console.log(resp.data.content);
})
.catch(e => {
console.log(e);
});
}
};
一开始我以为这可能与你使用蓝图有关,但不,我无法重现这个问题。这是我的设置:
from flask_cors import CORS
from flask import Flask, Blueprint, jsonify
auth = Blueprint('auth', __name__)
@auth.route('/check_passport')
def check_passport():
return jsonify(dict(message='Check passport'))
app = Flask(__name__)
app.register_blueprint(auth, url_prefix='/auth')
CORS(app). # comment out to see cors error
我用这个向端点发出请求的简单页面来测试它:(只需将它拖到浏览器窗口中并观看控制台(
<!DOCTYPE html>
<html>
<head>
<title>Cors Check</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script type='text/javascript'>
var url = 'http://127.0.0.1:5000/auth/check_passport';
// fetch
fetch(url).then(resp => resp.json()).then(data => {
console.log('SUCCESS')
console.log(data)
})
// or axios
axios.get(url).then(response => {
console.log('SUCCESS', response.data);
})
</script>
</head>
<body></body>
</html>
我可以看到它在使用CORS(app)
时工作得很好,但没有它就不行了。