Clarifai食品检测应用400授权错误与修改后404报错求助
第一次400错误修复方案
你最初遇到的400错误由两个问题导致:
- 传入的
model_id参数开头多了一个无效空格:" bd367be194cf45149e75f01d59f77ba7"前的空格会导致Clarifai SDK参数解析异常,最终鉴权头拼装失败触发报错。你后续改用Clarifai.FOOD_MODEL常量的写法是正确的,直接用这个预设常量即可避免手写model_id的拼写/格式错误。 - render函数中存在变量名大小写不匹配问题:state中定义的图片地址字段是
imageUrl,但你在解构时写成了imageURL,会导致食品识别组件无法正常拿到图片地址,需要同步修正。
// 修改前 const { input, imageURL, showModal, foodIngredients } = this.state; <FoodRecognition url={imageURL} // 其他属性 /> // 修改后 const { input, imageUrl, showModal, foodIngredients } = this.state; <FoodRecognition url={imageUrl} // 其他属性 />
更新后新报错的修复方案
你遇到的两个新报错为因果关系:
PUT http://localhost:3000/image/ 404 (Not Found)是核心问题,触发原因是本地后端服务没有对应/image路径的PUT接口,或后端服务异常:- 首先确认你的后端服务已正常启动,且监听端口确实为3000
- 检查后端路由配置,若路由定义为
/image(无末尾斜杠),请将请求地址改为http://localhost:3000/image(去掉末尾斜杠)即可解决404问题
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0是404的衍生问题:接口返回404时,默认会返回HTML格式的错误页面,你直接调用response.json()解析HTML内容就会触发格式错误,404问题修复后该报错会自动消失。你也可以补充响应状态判断,避免异常情况下的报错:
fetch("http://localhost:3000/image", { method: "put", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ url: this.state.input, }), }) .then((response) => { // 先判断请求是否成功,再解析JSON if (!response.ok) { throw new Error(`请求失败,状态码:${response.status}`); } return response.json(); }) .then((response) => { // 原有业务逻辑 if (response.length <= 0) { return this.setState({ input: "", foodIngredients: [response], }); } else { this.setState({ input: "", foodIngredients: response, }); } }) .catch(err => { console.error("后端请求异常:", err); })
内容的提问来源于stack exchange,提问作者Gautham Yadav
相关产品推荐
相关产品推荐

