前端
//App.js
import axios from 'axios'
import {useEffect, useState} from 'react'
import './App.css';
function App() {
const [something, setSomething] = useState({})
const url = "http://localhost:5000/data"
const input = "https://static.independent.co.uk/s3fs-public/thumbnails/image/2015/06/06/15/Chris-Pratt.jpg"
const func = async () => {
const {data} = await axios.post(url, {input : input})
setSomething(data)
}
useEffect(() => {
func()
}, [])
return (
<div className="App">
<h1>APP WORKING</h1>
{console.log("something : ",something)}
</div>
);
}
export default App;
后端
//demographics.js
const {ClarifaiStub, grpc} = require("clarifai-nodejs-grpc");
const stringify = require('json-stringify-safe');
const demographics = (req,res) => {
const stub = ClarifaiStub.grpc()
const metadata = new grpc.Metadata();
metadata.set("authorization", "Key #ClarifaiKey#");
stub.PostWorkflowResults(
{
workflow_id: "Demographics",
inputs: [
{data: {image: {url: req.body.input}}}
]
},
metadata,
(err, response) => {
if(response){
console.log("AGE :", response.results[0].outputs[4].data.regions[0].data.concepts[0])
here --> const data = stringify(response.results[0].outputs[4].data.regions, null, 2)
res.send(data)
}
else {
console.log(err)
res.status(400)
}
}
)
}
module.exports = {
demographics: demographics
}
我对“json-stringify-safe”包不是很有信心,但据我所知,nodejs-grpc clarifai 返回一个循环结构数据对象,直接使用时会抛出错误,所以“stringify(response.results[0] .outputs[4].data.regions, null, 2)" 将其转换为常规 json 对象。
人口统计模型适用于多个面孔,因此如果图片中有多个面孔,那么您可以从“response.results[0].outputs[4].data.regions”跟进
另外,在 server.js 中一定要包含
//server.js
...
const posts = require('./demographics.js')
const PORT = process.env.PORT || 5000
app.post('/data', posts.demographics)
...