【发布时间】:2020-02-29 06:12:10
【问题描述】:
我在带有 FETCH api 的 ReactJS 中有一段代码运行良好,但是当我尝试用 AXIOS 替换它时,即使我检查了文档,它也不能正常运行。
获取 API 的工作代码:
const signup = (user) => {
return fetch(`${API}/signup`, {
method: "POST",
headers: {
Accept: 'application/json',
"Content-Type": 'application/json'
},
body: JSON.stringify(user)
})
.then(response => {
return response.json();
})
.catch(err => {
console.log(err);
});
}
const clickSubmit = (event) =>{
event.preventDefault();
signup({name, email, password})
.then(data => {
if(data.error){
setValues({...values, error: data.error, success: false})
}
else{
setValues({...values, name: '', email: '', password: '', error:'', success:true})
}
})
}
不使用相同的代码,但使用 AXIOS 库:
import axios from 'axios';
const signup = (user) => {
return axios(`${API}/signup`, {
method: "POST",
headers: {
Accept: 'application/json',
"Content-Type": 'application/json'
},
data: JSON.stringify(user)
})
.then(response => {
return response.data;
})
.catch(err => {
console.log(err);
});
}
const clickSubmit = (event) =>{
event.preventDefault();
signup({name, email, password})
.then(data => {
if(data.error){
setValues({...values, error: data.error, success: false})
}
else{
setValues({...values, name: '', email: '', password: '', error:'', success:true})
}
})
}
用 axios 库编写上述代码后出现的错误是:
未处理的拒绝(TypeError):无法读取未定义的属性“错误”
使用 axios 的代码有什么问题?
注意:
显然我将其缩小到未定义的地方。
signup({name, email, password})
.then(data => {
if(data.error){
setValues({...values, error: data.error, success: false})
}
else{
setValues({...values, name: '', email: '', password: '', error:'', success:true})
}
})
}
.then() 块中的“数据”未定义,我不知道为什么 fetch api 工作正常。
【问题讨论】:
-
如果你添加它会起作用:return response.data;而不是返回响应;