本项目使用VUE开发前端界面,使用FLASK框架搭建后端服务器逻辑代码。
问题
通过前端页面请求网址时,F12控制台出现报错:
No ‘Access-Control-Allow-Origin‘ header
 
试错
首先,这不是后端服务器 nginx的问题,如下设置不起作用:
    server {
        listen       6000;
        server_name  localhost;
        location / {
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With';
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            return 204;
        }
        if ($request_method = 'POST') {
            add_header 'Access-Control-Allow-Origin' '*'; # 或者指定具体的源,例如:http://localhost:8080
            add_header 'Access-Control-Allow-Credentials' 'true'; # 如果需要携带cookie进行跨域请求,请添加此行
        }
            proxy_pass http://127.0.0.1:6000;  # 将请求代理到不同的端口上
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
 
第二,这不是VUE的问题,百度了很多VUE文件设置和npm install --save ****
办法
我们使用的是flask框架,问题出在 flask.
 Flask跨域问题可以通过CORS来解决。CORS是一个HTTP头,允许服务器告诉客户端,哪些源站点可以访问服务器上的资源。在Flask中,可以使用flask-cors库来简化CORS的配置。需要安装这个库:
pip install flask-cors
 
然后,在你的Flask应用中配置CORS:
from flask import Flask
from flask_cors import CORS
 
app = Flask(__name__)
CORS(app)
 
@app.route('/')
def hello_world():
    return 'Hello, cross-origin-world!'
 
如果需要更细致的控制,比如只允许特定的源访问资源,可以这样配置:
from flask import Flask
from flask_cors import CORS
 
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "http://example.com"}})
 
@app.route('/api/hello')
def hello_world():
    return 'Hello, cross-origin-world!'
 
在上面的这个例子中,只有来自http://example.com的请求才能访问/api/hello端点。










