React Native集成FatSecret API:获Token后请求返回200异常
解决React Native中FatSecret API POST请求返回200但无预期数据的问题
嘿,我看你碰到的这个问题挺典型的,咱们一步步来捋清楚:
问题回顾
你在开发React Native应用时,已经成功通过OAuth2.0拿到了FatSecret的Access Token,但用这个Token发起POST请求获取数据时,虽然返回状态码200,却拿不到预期的内容。你的相关代码和返回结果如下:
获取Access Token的代码
let form = new FormData(); var headers = new Headers(); headers.append("content-type", "application/json"), headers.append( "Authorization", "Basic " + base64.encode( <clientID>:<clientSecret>, ), ), form.append("grant_type", "client_credentials"); form.append("scope", "basic"); fetch("https://oauth.fatsecret.com/connect/token", { method: "POST", headers: headers, body: form, }) .then(res => res.json()) .then(json =>{this.calc(json.access_token)}) };
请求数据的代码
calc =(token)=>{ console.log(token) var headers2 = new Headers(); headers2.append("Content-Type", "application/json"); headers2.append( "Authorization", "Bearer "+token), fetch("https://platform.fatsecret.com/rest/server.api",{ method :"POST", headers:headers2, body:"method=foods.search&search_expression=toast&format=xml" }).then(res=>console.log(res)); }
返回结果
Response {type: "default", status: 200, ok: true, statusText: undefined, headers: Headers, …} headers: Headers {map: {…}} ok: true status: 200 statusText: undefined type: "default" url: "https://platform.fatsecret.com/rest/server.api" _bodyBlob: Blob {_data: {…}} _bodyInit: Blob {_data: {…}} __proto__: Object
问题根源
这里有两个关键问题:
- 请求头与请求体格式不匹配:你在
headers2里设置了Content-Type: application/json,但请求体是method=foods.search&...这种application/x-www-form-urlencoded格式的键值对,服务器收到后没法正确解析你的参数,所以返回了200但没有有效数据。 - 没有正确读取响应内容:你只是打印了
Response对象本身,而没有读取里面的实际响应体(比如Blob里的内容)。
解决方案
咱们一步步修改代码:
修改后的完整代码
calc = (token) => { console.log(token); var headers2 = new Headers(); // 修正Content-Type为表单编码格式,和请求体匹配 headers2.append("Content-Type", "application/x-www-form-urlencoded"); headers2.append("Authorization", "Bearer " + token); // 推荐换成format=json,后续处理数据更简单 const requestBody = "method=foods.search&search_expression=toast&format=json"; fetch("https://platform.fatsecret.com/rest/server.api", { method: "POST", headers: headers2, body: requestBody }) // 如果用xml就换成res.text(),用json就用res.json() .then(res => res.json()) .then(responseData => { console.log("成功获取数据:", responseData); // 这里可以开始处理你的业务逻辑了 }) .catch(error => { console.error("请求过程出错:", error); }); }
额外提醒
- 为什么之前返回200?因为FatSecret的API可能在接收到请求但解析参数失败时,还是返回200状态码,只是响应体里没有有效数据。
- 记得检查Access Token的有效期,避免后续请求因为token过期失败。
- 如果还是有问题,可以打印一下请求的完整信息,确认参数和headers都正确发送了。
内容的提问来源于stack exchange,提问作者한상혁
相关产品推荐
相关产品推荐

