各位Web developer的先進們好!
想請問各位關於angular5 post file到後端flask時(cross domain),
前後端log都顯示錯誤代號400(bad request),
後端沒有收到POST的檔案,
就連使用jQuery也一樣;
應該是瀏覽器的某項security policy造成,
我再與前端同環境下的postman向後端POST檔案時,
後端就能確實收到POST的檔案,
不知道是否遺漏掉某部份的設定,還麻煩各位先進們指點。
謝謝!
以下是我前後端的部份程式碼:
Flask (python):
from flask import request
from flask import Flask
from flask_cors import *
app = Flask(__name__)
CORS(app, supports_credentials=True)
@app.route('/api', methods=['POST'])
def getPost():
if request.method == 'POST':
req_file = request.files['file']
print(request.files['file'])
return 'received'
Angular5 (HttpClient):
var form = new FormData();
form.append("file", "/path/to/file");
const req = this
.http.post('http://flaskapiserver.url/api', form, {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded'),
})
.subscribe(
res => {
console.log(res);
}
);
jQuery (透過postman產生):
var form = new FormData();
form.append("file", "/path/to/file");
var settings = {
"async": true,
"crossDomain": true,
"url": "http://flaskapiserver.url/api",
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"Cache-Control": "no-cache"
},
"processData": false,
"contentType": false,
"mimeType": "multipart/form-data",
"data": form
}
$.ajax(settings).done(function (response) {
console.log(response);
});