I have this function:
const sendValidateJWTRequestFetch = (url: string, token: string) =>
fetch(url, {
method: 'GET',
mode: 'cors',
headers: {
Authorization: token,
'Access-Control-Allow-Origin': '*'}
})
.then(response =>
response.ok ? response : Promise.reject<Response>(response)
)
.then(response => response.json())
.then(data => data.Token)
It is working fine, but in prod enviroment I'm having some CORS issues, anyway, that's not the question, what I want to use axios
now for this get
. I'm trying this:
const sendValidateJWTRequest = (url: string, token: string) =>
axios.get(url, {
headers: {Authorization: token, 'Access-Control-Allow-Origin': '*'},
crossDomain: true
})
.then(resp => resp.data ? resp : Promise.reject<Response>(resp))
.then(response => response);
Not sure how to work with TS, Im getting this error:
How can I fix it?
EDIT: for getting the crossDomain: true
working I had to add this in the code:
declare module 'axios' {
export interface AxiosRequestConfig {
crossDomain: boolean;
}
}
Problem seems to be with Response
type - it's coming from fetch API and it's not matching what Axios is using. Basically those two libraries does not share typings. You need to use AxiosResponse
instead.
The other difference you might want to be careful about is that Axios does not handle errors in the same way as FetchAPI. In Fetch you have .ok
property and resolved promise, but in axios the promise would be rejected if status > 400 would be returned from server. So you don't need to reject the response yourself, but use .catch
if you need to handle it differently.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.