React Native对接Node.js时Axios POST报400及TypeError undefined问题求助
问题修复方案
1. 前端TypeError与请求参数问题修复
报错的根本原因是axios.post返回的是Promise异步对象,你没有加await直接同步解构属性,同时接口返回结构里根本不存在article字段,参数传递位置也错误。
修复后代码:
onPress={async () => { try { const pubKey = await AsyncStorage.getItem("pubKey"); const name = await AsyncStorage.getItem("name"); // post请求参数放在第二个参数(请求体),不要放在params里 const { data } = await axios.post( "http://127.0.0.1:4000/apply", { articleId: id, apubKey: pubKey, name: name, }, { headers: {'Content-Type' : 'application/json'}, } ); alert('지원 확인'); // 后端返回结构是{result:1},直接读对应字段即可 console.log(data.result); } catch (err) { // 捕获异常避免未处理Promise拒绝报错 console.error('请求出错', err); } }}
修改点说明:
- 点击函数加
async标记,所有异步操作加await等待执行完成 - 参数移到请求体位置,之前放在
params的参数会被拼到URL后,后端读req.body无法获取 - 加
try/catch捕获异常,避免运行时报错 - 按照后端实际返回结构读取数据,不要解构不存在的字段
2. 后端400报错与参数读取逻辑修复
你的后端参数读取逻辑完全混乱,一会儿读req.body.articleId一会儿读req.body.params.xxx,同时缺少错误响应逻辑。
修复后代码:
// 如果你是在app.js中通过app.use('/apply', require('./apply.js'))注册路由,这里路径保持"/"即可 router.post("/", function (req, res) { console.log("req.body: ", req.body); Article.findAll({ attributes: ["id", "db_pubKey", "db_title", "db_wtype"], where: { id: req.body.articleId // 直接从请求体读对应字段 } }) .then(result => { console.log("result : " + JSON.stringify(result)); const DB = result[0]; // 无需多余的JSON转译,直接取第一个查询结果 if (DB) { console.log("DB", DB); Apply.create({ db_apubKey: req.body.apubKey, // 不要加多余的.params层级 db_articleId: req.body.articleId, db_opubKey: DB.db_pubKey, db_title: DB.db_title, db_wtype: DB.db_wtype, db_name: req.body.name, db_accept: null }) .then(result => { console.log("result : " + result); res.status(201).json({ result: 1 }); }) .catch(err => { console.error("err : " + err); res.status(500).json({result: 0, msg: '创建失败'}); // 错误分支必须返回响应,不能挂起请求 }); } else { res.json({ result: 0 }); } }) .catch(err => { console.error("err : " + err); res.status(500).json({result:0, msg: '查询失败'}); next(err); }); });
额外配置确认:
- 先确认你后端入口文件已经配置了
body-parser中间件开启JSON解析,否则req.body会是undefined,在入口文件加以下代码:
const bodyParser = require('body-parser'); app.use(bodyParser.json());
- 之前换FormData出现404是路由路径不匹配导致的,确认路由注册规则和请求路径一致即可,如果使用FormData不要手动设置
Content-Type,axios会自动携带boundary字段。
内容的提问来源于stack exchange,提问作者mono
相关产品推荐
相关产品推荐

