AJAX/FLASK/JS: 如何将现有数组 POST 转换为端点?

AJAX/FLASK/JS: How to POST existing array into endpoint?

我正在尝试 POST 从 getTableData() 函数推送的 songFiles 数组(在 ajax 请求)进入 /api/fileNames 端点,然后发送到回调 postFileNames() post 数组,但我似乎无法让它工作。任何帮助将不胜感激,包括可能的其他方法。

我是使用 ajax 和烧瓶的初学者,我已经四处寻找解决方案,但似乎找不到适合我目标的任何解决方案,原谅我的知识匮乏

JavaScript代码

function getTableData() {
    $.ajax({
        method: "GET",
        url: "/api/getSong",
        dataType: "json",
        success: function(data) {
            createMusicTable();
            
            let indexObj = Object.keys(data.song).length;
            
            for (var i = 0; i < indexObj; i++) {
                var song = data.song[i]
                var id = data.song[i].song_id;
                var fileName = data.song[i].song_file + ".mp3";
                
                songFiles.push(fileName);
                appendMusic(song, id);
                
                songTitle.id = "s" + i;
                console.log("td-ok");
            }
            postFileNames(songFiles);
        }
    });
}
function postFileNames(data) {
    $.ajax({
        method: "POST",
        url: "/api/fileNames",
        dataType: "json", // data is an array, so not sure what to put here. 
        data: data, // not sure if correct
        success: function(data) {
            // should: post the data into the endpoint.
            // data is not logged, goes straight to error.
            console.log(data)
        },
        error: function() {
            console.log("cry")
        }
    })
}

FLASK 端点代码

@app.route("/api/fileNames", methods=['POST', 'GET'])
def fileNameStorage():
if request.method == 'POST':
    data = request.get_data() # not too sure what to do here either.
    return data 
else:
    return "error" # currently goes to 'return error'
@app.route("/api/fileNames", methods=['POST', 'GET'])
def fileNameStorage():
if request.method == 'POST':
    data = {
    "id": request.json["id"],
    "song_name": request.json["song_name"],
    "time_duration": request.json["time_duration"]
}
    return data, 200
else:
    return "error", 400 # currently goes to 'return error'

如果你会更漂亮:

@app.route("/songs/", methods=['GET', 'POST'])
def songs():
  return Songs().get_songs(), 200

在 routes.py 文件中 和另一个文件中的其他 类 和方法

如果映射数组元素有问题,可以尝试 jsonify(array) 或 json.dump(array)。