我有一个使用Flask-Restless创建的postgres数据库的API,并使用Apache提供。
在我收到多个"之后,我尝试使用基于javascript的前端访问API,API工作正常。 CORS错误访问控制允许原点"标题似乎与OPTIONS请求密切相关。
我尝试了以下修复
[1.在apache中启用cors] [1]
<VirtualHost *:80>
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type, Authorization"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
ServerName localhost
WSGIScriptAlias / /home/drmclean/bboxx/git/Smart-Solar-Server/SmartSolarServer.wsgi
WSGIScriptReloading On
<Directory /home/drmclean/bboxx/git/Smart-Solar-Server/>
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type, Authorization"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
Require all granted
Order allow,deny
Allow from all
</Directory>
Alias /docs /home/drmclean/bboxx/git/Smart-Solar-Server/swagger
<Directory /home/drmclean/bboxx/git/Smart-Solar-Server/swagger/>
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type, Authorization"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
Require all granted
Header set Access-Control-Allow-Origin "*"
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
<IfModule mod_rewrite.c>
RewriteEngine on
# Pass Authorization headers to an environment variable
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
2.Enable CORS using the flask-cors extension
app = Flask(__name__, static_folder= paths.base_path+'/swagger/')
cors = CORS(app)
3.使用flask-restless
启用CORSdef allow_control_headers(response):
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Credentials'] = 'true'
return response
bp = manager.create_api(REDACTED)
bp.after_request(allow_control_headers)
毋庸置疑,到目前为止还没有任何工作。
任何人都可以解释,
答案 0 :(得分:0)
选项3最接近,但您引用的文档仅适用于特定版本的Flask Restless,而不是最新版本。我建议将Flask's after_this_request processor与Flask Restless'预处理器
结合使用def allow_control_headers(**kw):
@after_this_request
def add_headers(response):
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Credentials'] = 'true'
return response
bp = manager.create_api({
...
'preprocessors: {'GET_SINGLE': [allow_control_headers]}
...
})