我有一个使用 Axios 的 Vue 前端来 POST 到我的 Flask API。我已经向我的 Flask 实例注册了flask_cors,但仍然收到 CORS 错误。
flask_cors app/__init__.py
注册
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from config import Config
from flask_marshmallow import Marshmallow
from flask_cors import CORS
app = Flask(__name__)
app.config.from_object(Config)
cors = CORS(app)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
ma = Marshmallow(app)
from . import routes, models
应用/路由.py
from flask import request, jsonify, current_app
from . import app, db
from .models import SetAnon
@app.route('/sets', methods=['POST'])
def sets():
data = request.get_json()
_set = SetAnon(
col1=data['somedata']
)
db.session.add(_set)
db.session.commit()
return "set saved", 201
Vue 前端正在使用 axios 发出 POST 请求:
import axios from 'axios'
const API_URL = 'http://127.0.0.1:5000'
export function saveSet(set) {
return axios.post(`${API_URL}/sets/`, set)
}
在浏览器控制台中收到此错误
xhr.js?ec6c:172 OPTIONS http://127.0.0.1:5000/sets/ 404 (NOT FOUND)
Access to XMLHttpRequest at 'http://127.0.0.1:5000/sets/' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
看起来像是尾随反斜杠的问题。您的 routes.py 将路由定义为'/sets'
但前端正在调用'/sets/'
。
将 routes.py 更改为此,它应该可以工作 -
从烧瓶导入请求、JSONIFY、current_app从。导入应用程序,数据库从 .models import SetAnon
@app.route('/sets/', methods=['POST']) # Added trailing backslash
def sets():
data = request.get_json()
_set = SetAnon(
col1=data['somedata']
)
db.session.add(_set)
db.session.commit()
return "set saved", 201