0

介绍

你好。在这个应用程序中,我正在使用 flask_login、fetch() 和 flask_cors 来预测正在预测的服装。一切都很好,直到我尝试使用注册用户帐户登录。


问题

所以目前,我已经创建了一个用户帐户,他可以在该帐户中做任何他想要的预测。所以在这里,我有一段代码,当用户点击带有 id 的预测按钮时#startbutton,它会向我的烧瓶后端发送一个 POST,预测并返回预测结果。

$("#startbutton").on("click", function(){
    let img = webcam.snap()
    $('#result').text( 'Predicting...');

    $.ajax({
        type: "POST",
        url:  "http://localhost:5000/predict",
        data: img,
        success: function(data){
            $('#result').text('Predicted Output: ' + data);
        }
    });
});

在我的后端,我创建了一个 API 路由来处理来自我的 javascript 的数据,并将记录添加到我的数据库中。在这里,我用来@login_required验证登录用户并将他的数据发布到数据库。我还添加了@cross_origin这样我可以从我的 ajax 调用中获取数据。

@app.route('/predict', methods=['GET','POST'])
@login_required
@cross_origin(origin='localhost',headers=['Content-Type','Authorization'],supports_credentials=True)
def predict():
    if request.method == 'POST':
        # get data from drawing canvas and save as image
        fileName, filePath = parseImage(request.get_data())
    
        # Decoding and pre-processing base64 image
        img = image.img_to_array(image.load_img(filePath, color_mode="grayscale", target_size=(28, 28))) / 255.
        # reshape data to have a single channel
        img = img.reshape(1,28,28,1)
    
        predictions = make_prediction(img)
    
        ret = ""
        for i, pred in enumerate(predictions):
            ret = "{}".format(np.argmax(pred))
            response = results[int(ret)]

            # dump new entry into db
            new_entry = Entry(user_id=current_user.id, filename=fileName, prediction=response, predicted_on=datetime.utcnow())
            add_entry(new_entry)

            return response
    return render_template("index.html", index=True, nav=True)

在我_init_.py声明我的应用程序和 CORS 的地方,我添加了supports_credentials=True以便 CORS 支持我的应用程序的凭据。

app = Flask(__name__)
CORS(app, supports_credentials=True)

但是,当我尝试调试并尝试在 localhost 中运行我的应用程序时,我使用现有用户帐户登录,并尝试进行预测。但我总是会收到一条Error 401(Unauthorized)错误消息,当我进入谷歌浏览器控制台查看错误时,我看到它将我识别为匿名用户。

jquery-3.5.1.js:10099 POST http://localhost:5000/predict 401 (UNAUTHORIZED)
send @ jquery-3.5.1.js:10099
ajax @ jquery-3.5.1.js:9682
(anonymous) @ index.js:49 <------- HERE
dispatch @ jquery-3.5.1.js:5429
elemData.handle @ jquery-3.5.1.js:5233

研究

我试图找出是否有人遇到同样的问题,并且我设法找到了一篇与我目前的情况相似的 SO 帖子。链接在这里。我试图理解它,但无法看到(或理解)他的最终解决方案。


编辑

好的,所以我尝试在 Mozilla 中重新制定我当前的 ajax 代码fetch(),据说它支持 cookie(我猜?),但最终仍然收到未经授权的消息。

$("#startbutton").on("click", function(){
    let img = webcam.snap()
    $('#result').text( 'Predicting...');

    fetch("http://localhost:5000/predict", {
      method: "POST",
      data: img,
      ContentType: 'application/json',
      credentials: 'include'
    })
    .then(function(data) {
      $('#result').text('Predicted Output: ' + data);
    }).catch((err) => {
      console.log(err)
    })
});

如果有人可以帮助我,真的会非常感激!:( 谢谢你! :)

4

1 回答 1

0

所以经过 3 天的痛苦之后,我看到一篇文章指出 ajax 调用默认是异步的,所以为了获取 cookie,我只需要设置asyncFalse. 所以我将我的 ajax 代码修改为下面的代码片段:

$("#startbutton").on("click", function(){
    let img = webcam.snap()
    $('#result').text( 'Predicting...');

    $.ajax({
        type: "POST",
        url:  "http://localhost:5000/predict",
        data: img,
        crossDomain: true,
        async: false,
        success: function(data){
            $('#result').text('Predicted Output: ' + data);
        }
    });
});

我知道这不是最佳解决方案(或者是 lmao),所以我愿意看到其他替代方案。

于 2021-02-11T02:56:27.137 回答