My page was using ajax requests but we are moving them to axios. I have changed the code but the response data is coming empty.
This was my old code:
export function getMList(params, onSuccess, onFailure) {
const url = `/admin/list`;
const {
name,
type
} = params;
return $.ajax({
type: 'GET',
url,
processData: false,
contentType: 'application/x-www-form-urlencoded',
data: $.param({name, type}),
success: (response) => {
onSuccess(response);
},
error: (error) => {
onFailure(error);
}
});
}
Now after changing it to axios it is :
export function getMList(params) {
const {
name,
type
} = params;
axios.get(`/admin/list`,params,{
headers : {'contentType': 'application/x-www-form-urlencoded'
}
}).then((res) => { return res; }, (err) => { return err; })
}
What am I doing wrong. Is it the data I am passing as params ?
The query is used here :
export function getMList(id, name, type) {
const encodedName = encodeURI(name);
return (dispatch) => {
dispatch(requestMList({ id }));
admin.getMList({ name: encodedName, type },
(response) => {
dispatch(receivedMList({ id, name, type, response }));
},
(error) => {
dispatch(failedMList(id));
}
);
};
}
axios request methods such as get
accepts two parameters, the request url and a request config object. Inside the config object you will need the data
key to set the request body (your params
) and the headers
key (your content-type).
export const getMList = (params) => {
return axios.get('/admin/list', {
data: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
}
Since axios returns a Promise, and the above function returns the axios request, you can then chain your "success" and "failure" logic using .then
and .catch
rather than passing them in as callbacks.
admin
.getMList({ name: encodedName, type })
.then((response) => dispatch(receivedMList({ id, name, type, response })))
.catch((err) => dispatch(failedMList(id, err)));