我有一个使用 Flask-Restless 创建并使用 Apache 提供服务的 postgres 数据库的 API。
在我收到多个似乎与 OPTIONS 请求密切相关的“CORS 错误 Access-Control-Allow-Origin”标头时,该 API 可以完美运行,直到我尝试使用基于 javascript 的前端来访问 API。
我尝试了以下修复
[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>
app = Flask(__name__, static_folder= paths.base_path+'/swagger/')
cors = CORS(app)
3.使用flask-restless启用CORS
def 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)
不用说,到目前为止还没有一个工作。
- 不会删除 CORS 警告。
- 似乎删除了某些端点的 CORS 错误,但没有删除其他端点,将其更改为 cors = CORS(app, response=r"/v1/*") 带回了最初已删除的 CORS 错误。
- 尽管我直接从文档中复制了语法,但由于“bp 没有属性 after_request”引发了语法错误。(这里)
谁能解释一下,
- 为什么上述修复没有消除 CORS 问题。
- 如何解决我的问题并有效地启用跨域资源共享?