如何在 React 中使用 axios 的 API 调用来使用 async await
2019-01-10
4517
我是 Web 开发新手。我正在使用
react.js
。因此,我想在这里使用
async/await
进行 API 调用。我正在使用
axios
。
现在,
我拥有的是
export function fetchToken(bodyjson) {
return (dispatch) => {
let url = LOGIN_PATH + "username=" + bodyjson.userName + "&password" + "=" + bodyjson.password;
return post(url, bodyjson)
.then((response) => {
if (response.status === 200) {
localStorage.setItem('user', bodyjson.userName);
localStorage.setItem('access_token', response.payload.access_token);
history.push('/');
dispatch({
type: LOGIN_SUCCESS,
data: response.payload,
})
}
else {
dispatch({
type: LOGIN_FAILED,
data: response.status,
});
}
})
}
}
而我的帖子服务是
export const post = (url, post_data) =>
axios.post(
apiGatewayEndpoint.apiGatewayEndpoint + url,
post_data,
{
headers: {
"Authorization": localStorage.getItem("access_token") !== null ? `Bearer ` + localStorage.getItem("access_token") : null,
"Content-Type": "application/json"
}
}
).then(data => {
if (data.status === HttpStatus.OK) {
return {
status: data.status,
payload: data.data
};
}
}).catch(err => {
return {
status: err.response.data,
payload: null
};
});
现在,我想在这里使用 async await。我对此非常困惑。我已经看了很多教程。
我想在
login
后立即调用 API。在此基础上,我想将用户重定向到不同的页面。
因此,有人可以帮助我使用这个
async-await
谢谢:-)
现在我正在使用它,
export function fetchToken(bodyjson) {
return async (dispatch) => {
let url = LOGIN_PATH + "username=" + bodyjson.userName + "&password" + "=" + bodyjson.password;
let response = await post(url, bodyjson)
if (response.status === 200) {
localStorage.setItem('user', bodyjson.userName);
localStorage.setItem('access_token', response.payload.access_token);
let fetchJd = FETCH_JD_ROOT_URL + page + "&" + size;
let newApiResponse = await get(fetchJd)
if (newApiResponse.status === 200) {
dispatch({
type: LOGIN_SUCCESS,
data: response.payload,
})
dispatch(sendUserJd(newApiResponse.payload));
}else {
dispatch({
type: LOGIN_FAILED,
data: response.status,
});
}
}
else {
dispatch({
type: LOGIN_FAILED,
data: response.status,
});
}
}
2个回答
对于 get 请求,您可以使用参数发送数据等。
export const getData = async () => {
try {
const { data } = await axios({
method: 'get', //you can set what request you want to be
url: `yoururl`,
params: {
// key values pairs
}
headers: {
'token': token
}
});
// run some validation before returning
return data;
} catch (e) {
console.log(e);
return .. some error object;
}
};
对于 post 请求
export const getData = async (params) => {
try {
const { data } = await axios({
method: 'post', //you can set what request you want to be
url: `url`,
data: params,
headers: {
'x-auth-Token': token
}
});
// run some validation before returning
return data;
} catch (e) {
console.log(e);
return .. some error object;
}
};
错误对象示例
{
status: 'error',
message: 'failed with something'
}
然后您可以像这样调用任何 api,
async componentDidMount() {
const data = await getData();
if(data.status === 'Something') {
// do something
}
}
Sarmad Shah
2019-01-10
您并不完全需要 async await 来实现此目的。
使用 then chain 方法
export function fetchToken(bodyjson) {
return (dispatch) => {
let url = LOGIN_PATH + "username=" + bodyjson.userName + "&password" + "=" + bodyjson.password;
return post(url, bodyjson)
.then((response) => {
if (response.status === 200) {
localStorage.setItem('user', bodyjson.userName);
localStorage.setItem('access_token', response.payload.access_token);
history.push('/');
dispatch({
type: LOGIN_SUCCESS,
data: response.payload,
})
//next api call
return post(newUrl, newBodyjson)
}
else {
dispatch({
type: LOGIN_FAILED,
data: response.status,
});
}
})
.then((newApiResponse) => {
//Do stuffs with new api response
})
}
}
但如果您只想使用 async-await 方法
export function fetchToken(bodyjson) {
return async (dispatch) => {
let url = LOGIN_PATH + "username=" + bodyjson.userName + "&password" + "=" + bodyjson.password;
let response = await post(url, bodyjson)
if (response.status === 200) {
localStorage.setItem('user', bodyjson.userName);
localStorage.setItem('access_token', response.payload.access_token);
history.push('/');
dispatch({
type: LOGIN_SUCCESS,
data: response.payload,
})
let newApiResponse = await post(newUrl, newBodyjson)
//Do stuffs with new api response
}
else {
dispatch({
type: LOGIN_FAILED,
data: response.status,
});
}
}
}
Ashish
2019-01-10