首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >烧瓶和JS之间的沟通不太顺利

烧瓶和JS之间的沟通不太顺利
EN

Stack Overflow用户
提问于 2021-09-14 09:00:36
回答 1查看 368关注 0票数 0

背景

作为制作图像识别AI应用程序的一个练习,我正在尝试测试一些用于开发它的工具。

为了制作一个简单的图像识别AI应用程序,我决定采用以下方法:

subject(frontend)

  • Using

  • 使用摄像头相关的HTML5 API拍摄
  • 及其一些与
    • 相关的ML库,作为这个JavaScript的fetch APIFlask的核心函数,用于前端和后端之间的通信。

我将要使用的工具是fetch APIFlaskHTML + JavaScript,所以我尝试制作一个示例代码来测试这些工具是如何工作的。

问题

JavaScript和Flask之间通过http进行的通信不起作用。问题可能是

Flask(server)

  • Something's

  • 未能将图像数据从JavaScript (前端)发送到,在处理json字符串时出错,data.
  • Something's和communication

的JavaScript代码和JavaScript代码出错

更多细节,请看下面的代码。

文件和代码

定义服务器端

  • app.py:的functions.
  • templates:文件返回给客户端的目录是placed.
  • index.html:HTML + JS摄像机代码,并向Flask.
  • post.html:发送http请求,以检查前端和服务器之间的通信是否正常。

文件合成

代码语言:javascript
复制
 ├── app.py
 └── templates
     └── index.html
      └── post.html

app.py

代码语言:javascript
复制
from flask import Flask
from flask import render_template, redirect, send_from_directory, request
from flask import jsonify

app = Flask(__name__)  
 
@app.route('/')  
def home():
    return render_template("index.html");

@app.route("/tmp",methods=['POST'])
def post():
    data = request.get_data()
    if not data:
       return "no data"
    else:
       return render_template("post.html")
    
  
if __name__ =="__main__":  
    app.run(debug = True)  

index.html

代码语言:javascript
复制
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Camera Test</title>
  <style>
  canvas, video{
    border: 1px solid gray;
  }
  </style>
</head>
<body>

<h1>HTML5カメラ</h1>

<video id="camera" width="300" height="200"></video>
<canvas id="picture" width="300" height="200"></canvas>
<form>
  <button type="button" id="shutter">シャッター</button>
  <button type="button" id="btn-send">send</button>
</form>

<audio id="se" preload="auto">
  <source src="camera-shutter1.mp3" type="audio/mp3">
</audio>

<script>

function sendServer(url, param){
  fetch(url, param)
    .then((response)=>{
      return response.json();
    })
    .then((json)=>{
      if(json.status){
        alert("送信に『成功』しました");
        setImage(json.result);    //json.resultにはファイル名が入っている
      }
      else{
        alert("送信に『失敗』しました");
        console.log(`json.status${json.status}`)
        console.log(json)
        console.log(`[error1] ${json.result}`);
      }
    })
    .catch((error)=>{
      alert("送信に『失敗』しました");
      //console.log(json)
      //console.log(json.result)
      console.log(`[error2] ${error}`);
    });
}


window.onload = () => {
  const video  = document.querySelector("#camera");
  const canvas = document.querySelector("#picture");
  const se     = document.querySelector('#se');

  /** カメラ設定 */
  const constraints = {
    audio: false,
    video: {
      width: 300,
      height: 200,
      facingMode: "user"   // フロントカメラを利用する
      // facingMode: { exact: "environment" }  // リアカメラを利用する場合
    }
  };

  /**
   * カメラを<video>と同期
   */
  navigator.mediaDevices.getUserMedia(constraints)
  .then( (stream) => {
    video.srcObject = stream;
    video.onloadedmetadata = (e) => {
      video.play();
    };
  })
  .catch( (err) => {
    console.log(err.name + ": " + err.message);
  });

  /**
   * シャッターボタン
   */
   document.querySelector("#shutter").addEventListener("click", () => {
    const ctx = canvas.getContext("2d");

    // 演出的な目的で一度映像を止めてSEを再生する
    video.pause();  // 映像を停止
    se.play();      // シャッター音
    setTimeout( () => {
      video.play();    // 0.5秒後にカメラ再開
    }, 500);

    // canvasに画像を貼り付ける
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
  });
   
   document.querySelector("#btn-send").addEventListener("click", ()=>{
    // Canvasのデータを取得
    const pic = canvas.toDataURL("image/png");  // DataURI Schemaが返却される

    // 送信情報の設定
    const param  = {
      method: "POST",
      headers: {
        "Content-Type": "application/json; charset=utf-8"
      },
      body: JSON.stringify({data: pic})
    };

    const SAVE_URL = "http://localhost:5000/tmp";
    // サーバへ送信
    console.log(param)
    
    sendServer(SAVE_URL, param);
  });

};
</script>
</body>
</html>

post.html

代码语言:javascript
复制
<body>
hello
</body>

我现在身上的窃听器是

index.html**

  • **中的sendServer函数可能会出现核心问题,没有json数据附加在来自

  • **

的http-response中

怎么啦?

如有任何资料,将不胜感激。

编辑过的

当我按“发送”按钮发送http请求时弹出的状态代码是202,因此发送请求(通过POST方法)可能会成功。在这种情况下,有什么问题吗?我猜sendServer函数被错误地实现了或者json的处理是错误的。

代码语言:javascript
复制
C:\Users\Naoki\yaruzo>python app.py
 * Serving Flask app 'app' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 955-089-816
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [19/Sep/2021 13:18:59] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [19/Sep/2021 13:19:01] "GET /camera-shutter1.mp3 HTTP/1.1" 404 -
127.0.0.1 - - [19/Sep/2021 13:19:01] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [19/Sep/2021 13:19:47] "POST /tmp HTTP/1.1" 200 -

编辑2

作为回答者的建议,我尝试删除JSONStringify并将图像数据直接放入http请求的body中,但现在我发现了另一个错误。已修改

代码语言:javascript
复制
//index.html
const param  = {
      method: "POST",
      headers: {
        "Content-Type": "application/json; charset=utf-8"
      },
      body: {data: pic}
    };

新误差

代码语言:javascript
复制
SyntaxError: Unexpected token o in JSON at position 1

错误发生在.catch函数的sendServer部分。

代码语言:javascript
复制
function sendServer(url, param){
  fetch(url, param)
    .then((response)=>{
      return response.json();
    })
    .then((json)=>{
      if(json.status){
        alert("送信に『成功』しました");
        setImage(json.result);    //json.resultにはファイル名が入っている
      }
      else{
        alert("送信に『失敗』しました");
        console.log(`json.status${json.status}`)
        console.log(json)
        console.log(`[error1] ${json.result}`);
      }
    })
    .catch((error)=>{
      alert("送信に『失敗』しました");
      //console.log(json)
      //console.log(json.result)
      console.log(`[error2] ${error}`);
    });
}
EN

回答 1

Stack Overflow用户

发布于 2021-09-14 10:10:02

正如你所怀疑的,问题要么是在sendServer方面,要么是在酒瓶或sendServer方面,我也认为问题在这两个方面,但我不能证实什么似乎是错误的。因此,有一些问题需要解决,您能否确认请求是否正在发送,以及返回了什么状态代码(您可以在网络选项卡下检查是否使用烧瓶调试或浏览器调试)浏览器应该显示状态代码以尝试发送请求。

第一解

因此,如果状态代码为404,那么请求中就会出现错误,通常是数据或发送的CORS与请求头一起传递。我怀疑第二个选项,所以我建议您在代码中添加以下内容,然后再尝试发送图像(用从本地发送请求的端口替换端口,或者只保留localhost)

代码语言:javascript
复制
#app.py
app = Flask(__name__)
CORS(app,resources={r"/*":{"http://localhost:{port}":"*","http://localhost":"*"}})

第二解

如果第一个解决方案不起作用,并且状态代码仍然是404,那么问题应该在发送的数据中。试着把(JSON.stringify)拿出来,看上去像这样,

代码语言:javascript
复制
//index.html
const param  = {
      method: "POST",
      headers: {
        "Content-Type": "application/json; charset=utf-8"
      },
      body: {data: pic}
    };
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69174873

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档