【问题标题】:getting error 400 with axios post request & undefined error使用 axios 发布请求和未定义的错误得到错误 400
【发布时间】:2021-12-13 08:25:10
【问题描述】:

我正在做一个项目来使用 react-native 将数据存储在 mysql 中。和 node.js 服务器 但我遇到了两个问题,一个是对象中的 TypeError:未定义,另一个是使用 axios 发布请求时出现错误 400。我试图用另一种方法来解决第二个问题(将参数更改为 formData - 但这不起作用,错误 404)对不起,如果这是一个愚蠢的错误,因为我是使用 react native 和 node.js 的新手。

反应原生代码

onPress={() => {
                    AsyncStorage.getItem("pubKey").then(pubKey => {
                      AsyncStorage.getItem("name").then(name => {
                        const {
                            data: { article }
                          } = axios.post("http://127.0.0.1:4000/apply",null,{
                            params: {
                              articleId: id,
                              apubKey: pubKey,
                              name: name,
                            },
                            headers: {'Content-Type' : 'application/json'},
                          });
                          alert('지원 확인')
                          console.log(article)
                      })
                    })
                  }}

[未处理的承诺拒绝:TypeError:未定义不是对象(评估'_axios$post.data.article')] [未处理的承诺拒绝:错误:请求失败,状态码为 400]

node.js (apply.js)

router.post("/", function (req, res) {
console.log("req.body.params: ",req.body)
console.log("req: ",req)
Article.findAll({
    attributes: ["id", "db_pubKey", "db_title", "db_wtype"],

    where: {
        id: req.body.articleId
    }
})
    .then(result => {
        console.log("result : " + JSON.stringify(result));

        let DB2 = JSON.stringify(result);
        let DB1 = JSON.parse(DB2);
        let DB = DB1[0];
        if (DB) {
            console.log("DB", DB);

            Apply.create({
                db_apubKey: req.body.params.apubKey,
                db_articleId: req.body.params.articleId,
                db_opubKey: DB.db_pubKey,
                db_title: DB.db_title,
                db_wtype: DB.db_wtype,
                db_name: req.body.params.name,
                db_accept: null
            })
                .then(result => {
                    console.log("result : " + result);
                    res.status(201).json({ result: 1 });
                })
                .catch(err => {
                    console.error("err : " + err);
                });
        } else {
            res.json({ result: 0 });
        }
    })
    .catch(err => {
        console.error("err : " + err);
        next(err);
    });
});

【问题讨论】:

  • 不是您的 400 响应的原因,但您需要等待 Axios 承诺的结果,然后再开始拉出 data

标签: node.js react-native axios


【解决方案1】:

所有 API 调用都是异步的,因此您需要使用适当的策略(例如 async/awaitthen/catch 方法)来处理异步操作。

使用async/await 方法:

onPress={async () => {
  try {
      const pubKey = await AsyncStorage.getItem("pubKey")
      const name = await AsyncStorage.getItem("name")
    
      const result = await axios.post("http://127.0.0.1:4000/apply", null, {
        params: {
          articleId: id,
          apubkey: pubKey,
          name: name,
        },
        headers: {'Content-Type' : 'application/json'},
      })
         
      const article = await result?.data?.article
    
      alert('지원 확인')
      console.log(article)

  } catch (error) {
    // do proper action on error/failure cases
    console.log(error)
  }
}}

注意:不要忘记为您的 API 调用使用 catch 方法。

注意:作为旁注,您不能在生产应用程序中调用http URL,它必须是https

注意:您可能需要指定 article 类型并传递它。

关于后端的 400 错误: 将此行 router.post("/", function (req, res) { 更改为:

router.post("/apply", function (req, res) {
 // rest of the codes ...

您忘记正确添加 API 名称。

【讨论】:

  • 我尝试通过您的实现重新实现。结果, Type error : undefined 已修复,但仍然出现错误 400 Request failed with status code 400 at node_modules/axios/lib/core/createError.js:15:17 in createError at node_modules/axios/lib/core/settle.js:16:9 in settle - ... 10 more stack frames from framework internals
  • 我已经用您的后端问题更新了我的答案。请看@mono
  • 我检查了您的答案,然后更改了我的代码,但这一次发生了 404 错误。 @novonimo
  • 您在router.post("/apply") 函数中添加了一些console.log,日志在这里很重要,您在调用apply API 时看到了什么? @mono
  • 也检查这个部分` where: { id: req.body.articleId }, You sent the id` with params 但是这里你从body中获取id,请检查实现和日志。 @mono
猜你喜欢
  • 2020-11-19
  • 1970-01-01
  • 2021-03-31
  • 1970-01-01
  • 1970-01-01
  • 2017-11-27
  • 2018-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多