React Native如何从AWS API Gateway POST请求获取自定义响应体?
排查步骤及解决方案
检查请求库的响应解析逻辑
如果你用的是RN自带的fetch,默认不会自动解析响应体,直接访问response.body会得到undefined,必须手动调用解析方法:fetch('https://your-api-endpoint/login', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ username: 'xxx', password: 'xxx' }) }) .then(async res => { // 必须先解析响应体,根据API返回格式选json()或text() const responseData = await res.json(); console.log(responseData.token); // 这里才能拿到JWT Token }) .catch(err => console.error(err));要是用
axios,确认没有错误配置拦截器导致响应体被修改,正常情况下axios会自动解析JSON响应,直接访问response.data即可。验证Lambda和API Gateway的响应格式
确保Lambda返回的是标准的API Gateway兼容格式,必须包含Content-Type: application/json头,且body是JSON字符串:// Lambda示例代码 exports.handler = async (event) => { // 业务逻辑... return { statusCode: 200, headers: { 'Content-Type': 'application/json', // 跨域相关头如果需要的话也要加上 'Access-Control-Allow-Origin': '*' }, body: JSON.stringify({ token: 'your-jwt-token', success: true }) }; };同时检查API Gateway的集成响应配置,确保没有把响应体转换成非JSON格式(比如纯文本),确认映射模板是
application/json且正确传递Lambda返回的内容。核对请求Headers是否和Postman一致
把RN请求里的Headers和Postman的Headers完全对齐,尤其是Content-Type和Accept字段,比如Postman里设置了Accept: application/json,RN里也要加上,避免API Gateway返回不同格式的响应。查看完整响应对象
不要只打印response.body,把整个响应对象转成字符串打印:fetch(...) .then(res => { console.log(JSON.stringify(res)); return res.json(); })有些RN版本的fetch响应中,原始响应内容可能存在于
_bodyInit或_bodyText字段,通过这些字段可以排查响应是否正确返回。
内容的提问来源于stack exchange,提问作者HBridges
相关产品推荐
相关产品推荐

