英文:
Data undefined in axios response
问题
在我的MERN应用中,登录页面的axios post响应数据给我报错如下:
登录响应错误TypeError: Cannot read properties of undefined (reading 'data')
这是我的axios post请求:
const login = async (e) => {
    e.preventDefault();
    try {
      //urls 
      const loginUrl = "http://localhost:4000/api/user/login";
      const customerUrl = "http://localhost:4000/api/stripe/customer";
      
      let response = await axios({
        method: "post",
        url: loginUrl,
        data: {
          email: loginEmail,
          password: loginPassword
        },
        headers: {
          "Content-Type": "application/json",
          "x-access-token": token, // 设置Content-Type头部
        },
      }).then((response) => setShow(true))
      // .then(data => response)
      .catch((error) => console.log("登录响应错误" + error))
这是我对于令牌等内容的处理:
if (response.data && response.data.token) {
        let token = response.data;
        setToken(token);
        console.log("登录成功。邮箱:" + email+ " 令牌:" + token)
        const response2 = await axios({
          url: customerUrl,
          data: {
            email: loginEmail,
          },
          headers: {
            "x-access-token": token,
          }
        });
        if (response2) {
          console.log("客户数据成功")
        } else {
          console.log("客户数据失败")
        }
        axios.all([response, response2], axios.spread((response, response2) => {
          console.log("响应1:" + response.data)
          console.log("响应2:" + response2.data)
        }))
        .catch((error) => {
          console.error("错误:" + error)
        });
        // 进一步处理令牌,如将其存储在localStorage中或重定向到新页面
      } else {
        // 处理响应中不存在令牌的情况
        console.error("响应中未找到令牌");
      }
    } catch (error) {
      console.log("从登录获取数据时出错" + error);
    }
后端不是问题,我已经使用Postman进行了测试,当我使用console.log时,响应也会显示为undefined。
英文:
Im creating a MERN app. The data in the axios post response for my login page is giving me this error
Error with Login ResponseTypeError: Cannot read properties of undefined (reading 'data')
This is my axios post
const login = async (e) => {
    e.preventDefault();
  
    try{
      //urls 
      const loginUrl = "http://localhost:4000/api/user/login";
      const customerUrl = "http://localhost:4000/api/stripe/customer";
      
      let response = await axios({
        method: "post",
        url: loginUrl,
        data: {
          email: loginEmail,
          password: loginPassword
        },
        headers: {
          "Content-Type": "application/json",
          "x-access-token": token, // Set the Content-Type header
        },
      }
    ).then((response) => setShow(true))
    // .then(data => response)
    .catch((error) => console.log("Error with Login Response" + error))
This is what I'm doing for the token and stuff
if (response.data && response.data.token) {
        let token = response.data;
        setToken(token);
        console.log("Login succesful. email: " + email+ "token: " + token)
        const response2 = await axios({
          url: customerUrl,
          data: {
            email: loginEmail,
          },
          headers: {
            "x-access-token": token,
          }
        });
        if (response2) {
          console.log("Customer Data Success")
        } else {
          console.log("Customer Data Failure")
        }
        axios.all([response, response2], axios.spread((response, response2) => {
          console.log("RESPONSE 1: " + response.data)
          console.log("RESPONSE 2:" + response2.data)
        }))
        .catch((error) => {
          console.error("ERROR: " + error)
        });
        // Perform further actions with the token, such as storing it in localStorage or redirecting to a new page
      } else {
        // Handle the case when the token is not present in the response
        console.error("Token not found in response");
      }
    } catch (error) {
      console.log("Error getting data from login" + error);
    }
the backend isn't the problem, I already tested it with postman, The response is logging as undefined too when I console.log
答案1
得分: 1
你正在使用.then()在异步调用上。尝试使用以下方法调试response是什么。
try {
  const response = await axios({
    // ... 你的配置
  });
  console.log(response); // 用于调试响应内容。
  if (response?.data) {
    setShow(true);
  } else {
    // 可能需要一些额外的错误处理来 gracefully 处理缺少 `data` 的情况。
  }
} catch (error) {
  console.log(`登录响应出错 ${error}`);
}
注意:这里使用了可选链来检查 response 对象上的 data。
英文:
You are using .then() and on an asynchronous invocation. Try using the following to debug what response is.
try {
  const response = await axios({
    // ... your config
  });
  console.log(response); // To debug what the response is.
  if (response?.data) {
    setShow(true);
  } else {
    // Maybe some additional error handling to gracefully handle missing `data`.
  }
} catch (error) {
  console.log(`Error with Login Response ${error}`);
}
Note: This uses optional chaining to check for data on your response object.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论