首页 > 解决方案 > Axios POST 请求返回代码中的空数据,但在 Insomnia/Postman 工作

问题描述

我在 react native 中遇到了 axios 请求的问题,它发送了一个名为“cpfcnpj”的 id 号的帖子,这个数字在 PostgresSQL 中获取并返回相应的行。它在 Insomnia 和 Postman 中完美返回行,但在代码中,response.data 以空数组“[]”的形式出现,但代码为 200,有人可以帮我吗?我很确定这可能是语法错误。

(这发生在 localhost 和托管 API 的 heroku 上)

AXIOS 代码:

      
       await axios({
        method: 'post',       
         headers: {
        "Content-Type": "application/json",
      },
        url: 'https://api-carnedecasa.herokuapp.com/api/login',
        data: {
          cpfcnpj:"15004799793"
        }
      }).then((response) => {
        console.log(response.data);
      }, (error) => {
        console.log(error);
      });; 

节点银行代码:


        process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;

        (async () => {
           
            try {
              var res = await pool.query('SELECT * FROM cliente WHERE cpfcnpj = $1', [req.body.cpfcnpj])              
              var data = res.rows
            } finally {
              result.json(data)
             
            }
           
          })().catch(err => console.log(err.stack))
                
          
     }, 

要求在失眠症上正常工作:

在此处输入图像描述

非常感谢你们!

标签: node.jspostgresqlreact-nativepostaxios

解决方案


解决了我在标题和 JSON.stringify 正文中添加 'Accept': 'application/json' 的问题!

  const rawResponse = await axios(`https://api-carnedecasa.herokuapp.com/api/login`, {
              method: 'POST',
              headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
              },
              data: JSON.stringify({cpfcnpj: "15060655709"})
            }).then(function(response) {
                console.log(response.data);

推荐阅读