首页 > 解决方案 > 错误:无法读取未定义的属性“令牌”

问题描述

api在方法中有一个函数onSubmit,它向服务器发出请求:

onSubmit: async (formValues) => {
          setSubmitting(true);
          try {
              const res = await api('api/auth/register', {
                  method:'POST',
                  body: JSON.stringify(formValues)
              });
              if(Array.isArray(res)){              
                  setErrorMessage(res[0].message);                  
              } else {
                 const token = res.token.token;   
                 localStorage.setItem('myToken', token);     
                 history.push("/home");
             }
          } catch(e) { 
              console.error(e);
          } finally {
              setSubmitting(false);
          }   
       },  
    });

函数api在一个单独的文件中,如下所示:

export const api = async (url, args) => { 

  const response = await fetch(`${apiUrl}${url}`, {
   ...args,
    headers: {
      "Content-type": "application/json; charset=UTF-8 ",
      "Accept": 'application/json',
      ...args.headers,  
    },
  });
      
 return response.json();      
}

这个函数是为了方便而创建的。但现在我不需要这个功能。我需要来自api方法内部的代码onSubmit。也就是说,该功能api根本不存在。

我做到了:

onSubmit: async (formValues) => {
          setSubmitting(true);
          try {
              const resf = await fetch(`${apiUrl}api/auth/register`, {
                  method:'POST',
                  body: JSON.stringify(formValues),
                  headers: {
                    "Content-type": "application/json; charset=UTF-8 ",
                    "Accept": 'application/json', 
                  }
              });
              const res = resf.json();
              
              if (Array.isArray(res)){              
                  setErrorMessage(res[0].message);                  
              } else {
                 const token = res.token.token;   
                 localStorage.setItem('myToken', token);     
                 history.push("/home");
             }
          } catch(e) { 
              console.error(e);
          } finally {
              setSubmitting(false);
          }   
       },  
    });

但我有错误:

TypeError:无法读取未定义的属性“令牌”

为什么会出现这个错误?

标签: reactjs

解决方案


尝试使用awaitfor,resf.json()因为调用.json()会为您提供尚未加载的 http 响应正文的另一个承诺。

const res = await resf.json();

推荐阅读