element-ui + vue + node.js 与 服务器 Python 应用的跨域问题
跨越问题解决的两种办法:
1. 在 config => index.js 中配置 proxyTable 代理:
proxyTable: { '/charts': { target: 'http://localhost:5001', changeOrigin: true, pathRewrite: { '^/charts':'/charts' } } }
说明: /charts:以其开头的所有路径请求转发,.changeOrigin 参数为true: 本地会虚拟一个服务器接收请求,并转发该请求
2. 在 config => dev.env.js 中配置BASE_API,由后端应用解决
module.exports = { NODE_ENV: '"development"', ENV_CONFIG: '"dev"', BASE_API: '"http://localhost:5001"' }
在Python应用中处理跨域问题:
- 方法1:使用 flask_cors
from flask_cors import CORS # 解决跨域问题
from flask import Flask
app = Flask(__name__)
app.config.from_object(base_conf.config["development'])
# CORS(app, resources={"/charts/*",{"origins": "*"})
CORS(app, supports_credentials=True)
- 方法2: 对 请求头部添加信息
@app.after_request def af_request(resp): """ #请求钩子,在所有的请求发生后执行,加入headers。 :param resp: :return: """ resp = make_response(resp) resp.headers['Access-Control-Allow-Origin'] = '*' resp.headers['Access-Control-Allow-Methods'] = 'GET,POST' resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type' return resp
- nginx
server { listen 8001; access_log /var/log/openresty/access.log basic; location / { proxy_pass http://127.0.0.1:9527; # proxy_pass http://node; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Nginx-Proxy true; proxy_redirect off; }
location /charts {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $http_host;
proxy_cookie_path /charts /charts;
}
}
或者,打包之后:
server { listen 80; access_log /var/log/openresty/access.log basic; location / { root /opt/app/reports-web/dist; index index.html index.htm; } location /charts { proxy_pass http://127.0.0.1:5000; proxy_set_header Host $http_host; proxy_cookie_path /charts /charts; #proxy_cookie_domain localhost:80 http://127.0.0.1:5000; } }
- Python
from flask import render_template, Flask import os print(os.path.abspath(os.curdir)) app = Flask(__name__, static_folder="F:/workspace/reports/web/dist/static", template_folder="F:/workspace/reports/web/dist") @app.route('/') def index(): return render_template('index.html') """ 其他与前端交互的接口与视图 """ @app.route('/') def favicon(): return app.send_static_file("web/favicon.ico") if __name__ == '__main__': app.run(host='0.0.0.0', port=8000, debug=True)