azure-ai-vision-faceanalyzer 不适用于 React JS

问题描述 投票:0回答:1

根据azure人脸活体检测文档,我创建了一个会话并在服务器端获取了令牌,但在客户端我使用React JS。 我按照 .npmrc 设置的 link 并安装了库 npm install azure-ai-vision-faceanalyzer

之后我粘贴从会话响应中获取的令牌 当我运行该项目时,我在控制台中看到了白页和这样的错误

获取http://localhost:5173/faceanalyzer-assets/js/AzureAIVisionFace_SIMDBundle.js net::ERR_ABORTED 404(未找到)

import React, { useRef } from 'react';

// Step 1: Import the web component.
import "azure-ai-vision-faceanalyzer";

const AzureAIVisionFaceAnalyzerComponent = () => {
    const containerRef = useRef(null);
    // Step 2: Create the faceanalyzer element, set the token and upgrade the element.
    let azureAIVisionFaceAnalyzer = document.createElement("azure-ai-vision-faceanalyzer");
    customElements.upgrade(azureAIVisionFaceAnalyzer);
    azureAIVisionFaceAnalyzer.token = "***TOKEN***";
    azureAIVisionFaceAnalyzer.addEventListener('analyzed', (event) => {
            // The event.result, which is FaceAnalyzedResult interface, contains the result of the analysis. 
            console.log(event);
        });
    if (containerRef.current) {
        containerRef.current.appendChild(azureAIVisionFaceAnalyzer);
    }
    
    return <div ref={containerRef}></div>;
};

function App() {
  return (
    <div className="App">
      <AzureAIVisionFaceAnalyzerComponent />
    </div>
  );
}

export default App;
javascript reactjs azure
1个回答
0
投票
  • azure-ai-vision-faceanalyzer
    包在 npm 注册表中不可用,这导致了 404 错误。

enter image description here

这里我直接使用Azure的REST API与Axios HTTP客户端。

Index.js(带有 Express 服务器端的 Node.js):

const express = require('express');
const axios = require('axios');
const cors = require('cors');

const app = express();
const port = 5000;

app.use(cors());
app.use(express.json());

const subscriptionKey = "YOUR_AZURE_FACE_API_SUBSCRIPTION_KEY";
const endpoint = "YOUR_AZURE_FACE_API_ENDPOINT";

app.post('/analyze', async (req, res) => {
  const { image } = req.body;

  const url = `${endpoint}/face/v1.0/detect?returnFaceId=true&returnFaceAttributes=qualityForRecognition`;

  try {
    const response = await axios.post(url, image, {
      headers: {
        "Ocp-Apim-Subscription-Key": subscriptionKey,
        "Content-Type": "application/octet-stream"
      }
    });

    res.json(response.data);
  } catch (error) {
    console.error("Error analyzing face:", error);
    res.status(500).send("Error analyzing face.");
  }
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

客户端React JS:

  • 创建一个
    FaceLivenessDetection.js
    文件。
import React, { useState } from 'react';
import axios from 'axios';

const FaceLivenessDetection = () => {
  const [image, setImage] = useState(null);
  const [result, setResult] = useState(null);
  const [loading, setLoading] = useState(false);

  const handleImageUpload = (e) => {
    setImage(e.target.files[0]);
  };

  const analyzeFaceLiveness = async () => {
    if (!image) {
      alert("Please upload an image first.");
      return;
    }

    const formData = new FormData();
    formData.append("image", image);

    try {
      setLoading(true);
      const response = await axios.post('http://localhost:5000/analyze', formData, {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      });

      setResult(response.data);
    } catch (error) {
      console.error("Error analyzing face:", error);
      alert("Error analyzing face. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <h1>Face Liveness Detection</h1>
      <input type="file" accept="image/*" onChange={handleImageUpload} />
      <button onClick={analyzeFaceLiveness} disabled={loading}>
        {loading ? "Analyzing..." : "Analyze Face"}
      </button>
      {result && (
        <div>
          <h2>Analysis Result</h2>
          <pre>{JSON.stringify(result, null, 2)}</pre>
        </div>
      )}
    </div>
  );
};

export default FaceLivenessDetection;

App.js:

import React from 'react';
import './App.css';
import FaceLivenessDetection from './FaceLivenessDetection';

const App = () => {
  return (
    <div className="App">
      <header className="App-header">
        <FaceLivenessDetection />
      </header>
    </div>
  );
};

export default App;

客户端应用程序:

enter image description here

enter image description here

服务器应用程序:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.