我编写了一个集中式函数来处理所有axios请求,如下所示:
export async function callApi(apiOptions) {
let headers = {
'X-Client-ID': '********************', //using * for security purposes
'X-Client-Secret': '******************', //same
};
if (apiOptions.headers !== undefined) {
apiOptions.headers.forEach(header => {
headers[header.name] = header.value;
});
}
let options = {};
options = {
url: apiOptions.endpoint,
method: apiOptions.method,
baseURL: process.env.REACT_APP_API_BASE_URL,
headers: headers,
data: apiOptions.data,
};
await axios(options)
.then(response => {
console.log(response); //200 status code
return response;
})
.catch(error => {
return error;
});
}
该函数接受一个“options”对象,并相应地发送一个axios请求,然后将响应返回给调用方。但是,当我调用函数并记录响应时,它会显示“未定义”。
useEffect(() => {
let options = {
endpoint: '/password-policy',
method: 'GET',
};
callApi(options)
.then(response => {
console.log('RES', response); // consoles 'undefined'
})
.catch(err => {
console.log('err', err);
});
}, [width]);
有人能告诉我哪里出了问题吗。提前一吨谢谢。
发布于 2022-08-11 10:40:14
您需要返回callApi
return await axios(options)
.then(response => {
console.log(response); //200 status code
return response;
})
.catch(error => {
return error;
});尽管如此,将回调和异步和等待混合起来并不好,您可以简化它:
export async function callApi(apiOptions) {
let headers = {
'X-Client-ID': '********************', //using * for security purposes
'X-Client-Secret': '******************', //same
};
if (apiOptions.headers !== undefined) {
apiOptions.headers.forEach(header => {
headers[header.name] = header.value;
});
}
let options = {};
options = {
url: apiOptions.endpoint,
method: apiOptions.method,
baseURL: process.env.REACT_APP_API_BASE_URL,
headers: headers,
data: apiOptions.data,
};
const response = await axios(options)
console.log(response); //200 status code
return response;
}https://stackoverflow.com/questions/73319216
复制相似问题