reactjs - 错误:无法读取未定义的属性“令牌”
问题描述
我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:无法读取未定义的属性“令牌”
为什么会出现这个错误?
解决方案
尝试使用await
for,resf.json()
因为调用.json()
会为您提供尚未加载的 http 响应正文的另一个承诺。
const res = await resf.json();
推荐阅读
- c# - task.run 为 c# 并行运行
- c# - 使用 Dapper 从 C# 调用存储过程时遇到问题
- mysql - Aurora 无服务器未从 CLI 和 mysql workbrench 连接
- ios - Xcode 10 (10A255) 错误:
:0: 错误:重复的输入文件 - c# - EF CORE 无时间戳的乐观并发
- copy - 如何复制 eststo
- javascript - 如何在 firebase 数据库中获取 push() 的引用?
- hangouts-chat - 单击 Google Chat Bot 交互按钮时出错
- angular - 为 ag-Grid 动态设置属性
- google-knowledge-graph - 向知识面板添加信息