我已经调用了一个axios,then()和catch()完美地记录了数据,但是当我返回它时,它将等待的变量设置为undefined
这里是axios文件
import axios from "axios";
const api = axios.create({
baseURL: "http://localhost:8080/",
});
export const loginManager = async (values) => {
const response = await api
.post("auth/login", values)
.then((res) => {
console.log(res.data);
})
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
return error.response.data
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser
// and an instance of http.ClientRequest in node.js
console.log(error.request);
return error.request
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
return error.message
}
});
return response
};
export default api;
这里是我调用它的组件
const LoginPage = () => {
const formik = useFormik({
initialValues: {
email: "",
password: "",
},
validate: globalLoginHandler,
validateOnBlur: false,
validateOnChange: false,
onSubmit: async (values) => {
toast.loading("Please Wait", { duration: 2000 });
const data = await loginManager(values);
},
});
数据必须有响应或错误对象
1条答案
按热度按时间wecizke31#
如果你使用的是async/await,你不必使用.then(),你可以简单地记录response.data。