gpt4 book ai didi

flask - 从 Vue 上传文件到 Flask CORS 不起作用

转载 作者:行者123 更新时间:2023-12-03 17:26:36 25 4
gpt4 key购买 nike

我正在尝试将文件从 vue 上传到 flask ,但我得到了

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/upload. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)..



这是我的 Vue 代码:
<script>
var Vue = require('vue');
Vue.use(require('vue-resource'));
export default {
name: 'app',
methods: {
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
let data = new FormData();
data.append('file', files[0]);
Vue.http.post('http://localhost:5000/upload', this.fileUploadFormData, function (data) {
alert('good')
});
}
}
}
</script>

这是我的 app.py
import os

from flask import Flask, render_template, app, send_file, request, jsonify, flash, redirect, url_for
from livereload import Server
from werkzeug.utils import secure_filename
from pandas import read_csv
from flask_cors import CORS, cross_origin


app = Flask(__name__)
cors = CORS(app, resorces={r'/*': {"origins": '*'}})
app.config['CORS_HEADER'] = 'Content-Type'


UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


@app.route('/', methods=['GET', 'POST'])
@cross_origin(origin='*', headers=['Content-Type', 'Authorization'])
def upload_file():
return send_file('static/html/index.html')


@app.route('/upload', methods=['POST'])
@cross_origin(origin='*', headers=['Content-Type', 'Authorization'])
def uploadFile():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file:
filename = secure_filename(file.filename)
full_filename = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(full_filename)
df = read_csv(full_filename, error_bad_lines=False, warn_bad_lines=False)
return str(df.to_json())
#return redirect(url_for('upload_file', file=filename))


if __name__ == "__main__":
app.debug = True
server = Server(app.wsgi_app)
#server.serve()
app.run()

最佳答案

在这一行:cors = CORS(app, resorces={r'/*': {"origins": '*'}})你有一个错字。更改resorcesresources .

关于flask - 从 Vue 上传文件到 Flask CORS 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42400108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com