mono
mono

Reputation: 69

getting error 400 with axios post request & undefined error

I'm making a project to store the data in mysql using react-native. and node.js server but i faced two problems One is TypeError in object : undefined and the other is getting error 400 with axios post request. I trying to another way for solve second problem (chage the param to formData - but this is doesn't work error 404) Sorry if this is a stupid mistake, as i am new to working with react native and node.js.

React native code

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)
                      })
                    })
                  }}

[Unhandled promise rejection: TypeError: undefined is not an object (evaluating '_axios$post.data.article')] [Unhandled promise rejection: Error: Request failed with status code 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);
    });
});

Upvotes: 0

Views: 2477

Answers (1)

nima
nima

Reputation: 8915

All API calls are asynchronous, so you need to handle an asynchronous action with proper strategies like async/await or then/catch method.

With the async/await method:

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)
  }
}}

Note: don't forget to use catch method for your API calls.

Note: as a side note, you can't call an http URL in production application, it must be an https

Note: you might need to specify the article type and pass it.

About the 400 error on your backend side: change this line router.post("/", function (req, res) { to :

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

You've forgotten to add your API name correctly.

Upvotes: 1

Related Questions