from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/',methods=['GET','POST'])
def getdata():
text = str(request.args.get("excel_file_name"))
return text
我发现要忽略这个错误,你应该使用flask_cors(我安装在pythonanywhere中)。我注意到,当我编写 from Flask_cors import CORS 时,请求的状态返回了 500,并且页面显示 Something goneError: -(Something goneError while attempts to load this Website; Please try again later.(与下面相同的代码有效)在本地主机服务器中成功)
from flask import Flask,request
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/',methods=['GET','POST'])
def getdata():
text = str(request.args.get("excel_file_name"))
return text
if __name__ == '__main__':
app.run(debug=True)
这是js代码(但是当我手动使用method[get]时也会显示错误)
document.getElementById("btn-submit").addEventListener("click",function(){
var fd = new FormData();
fd.append("excelfiles",document.getElementById("input_file").files[0]);
sendexcel("fd")
});
function sendexcel(objet){
var xml = new XMLHttpRequest();
xml.open("POST","https://sifo13.pythonanywhere.com/",true);
xml.onreadystatechange = function(){
if(this.readyState = 4 && this.status ==200){
var reponce = this.responseText;
alert(reponce)
}
}
xml.send("excel_file_name="+objet)
}
我假设您想通过 AJAX 向服务器发送文件。以下示例向您展示了如何在 pythonanywhere 上轻松实现此项目。我为此使用
Fetch API。有关服务器端代码的更多信息,我推荐this文章。
from flask import (
Flask,
render_template,
request
)
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.post('/data')
def getdata():
file = request.files.get('file')
return 'Got a file.' if file else 'Got no file.'
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Index</title>
</head>
<body>
<form name="my-form">
<input type="file" name="file" />
<input type="submit" />
</form>
<script type="text/javascript">
(function() {
const form = document.querySelector('form[name="my-form"]');
form.addEventListener('submit', function(evt) {
evt.preventDefault();
fetch('/data', { method: 'post', body: new FormData(this) })
.then(resp => resp.ok && resp.text())
.then(console.log);
});
})();
</script>
</body>
</html>