在axios响应中未定义数据。

huangapple go评论107阅读模式
英文:

Data undefined in axios response

问题

在我的MERN应用中,登录页面的axios post响应数据给我报错如下:

  1. 登录响应错误TypeError: Cannot read properties of undefined (reading 'data')

这是我的axios post请求:

  1. const login = async (e) => {
  2. e.preventDefault();
  3. try {
  4. //urls
  5. const loginUrl = "http://localhost:4000/api/user/login";
  6. const customerUrl = "http://localhost:4000/api/stripe/customer";
  7. let response = await axios({
  8. method: "post",
  9. url: loginUrl,
  10. data: {
  11. email: loginEmail,
  12. password: loginPassword
  13. },
  14. headers: {
  15. "Content-Type": "application/json",
  16. "x-access-token": token, // 设置Content-Type头部
  17. },
  18. }).then((response) => setShow(true))
  19. // .then(data => response)
  20. .catch((error) => console.log("登录响应错误" + error))

这是我对于令牌等内容的处理:

  1. if (response.data && response.data.token) {
  2. let token = response.data;
  3. setToken(token);
  4. console.log("登录成功。邮箱:" + email+ " 令牌:" + token)
  5. const response2 = await axios({
  6. url: customerUrl,
  7. data: {
  8. email: loginEmail,
  9. },
  10. headers: {
  11. "x-access-token": token,
  12. }
  13. });
  14. if (response2) {
  15. console.log("客户数据成功")
  16. } else {
  17. console.log("客户数据失败")
  18. }
  19. axios.all([response, response2], axios.spread((response, response2) => {
  20. console.log("响应1:" + response.data)
  21. console.log("响应2:" + response2.data)
  22. }))
  23. .catch((error) => {
  24. console.error("错误:" + error)
  25. });
  26. // 进一步处理令牌,如将其存储在localStorage中或重定向到新页面
  27. } else {
  28. // 处理响应中不存在令牌的情况
  29. console.error("响应中未找到令牌");
  30. }
  31. } catch (error) {
  32. console.log("从登录获取数据时出错" + error);
  33. }

后端不是问题,我已经使用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

  1. Error with Login ResponseTypeError: Cannot read properties of undefined (reading 'data')

This is my axios post

  1. const login = async (e) => {
  2. e.preventDefault();
  3. try{
  4. //urls
  5. const loginUrl = "http://localhost:4000/api/user/login";
  6. const customerUrl = "http://localhost:4000/api/stripe/customer";
  7. let response = await axios({
  8. method: "post",
  9. url: loginUrl,
  10. data: {
  11. email: loginEmail,
  12. password: loginPassword
  13. },
  14. headers: {
  15. "Content-Type": "application/json",
  16. "x-access-token": token, // Set the Content-Type header
  17. },
  18. }
  19. ).then((response) => setShow(true))
  20. // .then(data => response)
  21. .catch((error) => console.log("Error with Login Response" + error))

This is what I'm doing for the token and stuff

  1. if (response.data && response.data.token) {
  2. let token = response.data;
  3. setToken(token);
  4. console.log("Login succesful. email: " + email+ "token: " + token)
  5. const response2 = await axios({
  6. url: customerUrl,
  7. data: {
  8. email: loginEmail,
  9. },
  10. headers: {
  11. "x-access-token": token,
  12. }
  13. });
  14. if (response2) {
  15. console.log("Customer Data Success")
  16. } else {
  17. console.log("Customer Data Failure")
  18. }
  19. axios.all([response, response2], axios.spread((response, response2) => {
  20. console.log("RESPONSE 1: " + response.data)
  21. console.log("RESPONSE 2:" + response2.data)
  22. }))
  23. .catch((error) => {
  24. console.error("ERROR: " + error)
  25. });
  26. // Perform further actions with the token, such as storing it in localStorage or redirecting to a new page
  27. } else {
  28. // Handle the case when the token is not present in the response
  29. console.error("Token not found in response");
  30. }
  31. } catch (error) {
  32. console.log("Error getting data from login" + error);
  33. }

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是什么。

  1. try {
  2. const response = await axios({
  3. // ... 你的配置
  4. });
  5. console.log(response); // 用于调试响应内容。
  6. if (response?.data) {
  7. setShow(true);
  8. } else {
  9. // 可能需要一些额外的错误处理来 gracefully 处理缺少 `data` 的情况。
  10. }
  11. } catch (error) {
  12. console.log(`登录响应出错 ${error}`);
  13. }

注意:这里使用了可选链来检查 response 对象上的 data

英文:

You are using .then() and on an asynchronous invocation. Try using the following to debug what response is.

  1. try {
  2. const response = await axios({
  3. // ... your config
  4. });
  5. console.log(response); // To debug what the response is.
  6. if (response?.data) {
  7. setShow(true);
  8. } else {
  9. // Maybe some additional error handling to gracefully handle missing `data`.
  10. }
  11. } catch (error) {
  12. console.log(`Error with Login Response ${error}`);
  13. }

Note: This uses optional chaining to check for data on your response object.

huangapple
  • 本文由 发表于 2023年6月12日 23:55:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76458348.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定