如何将fetch转换为axios?



我想把我的项目从使用fetch改为axios。当我试图改变它时,我无法让它像我使用fetch时应该的那样工作。我得到了这个错误:response。Json不是一个函数。(在'response.json()'中,'response.json()'Json ' is undefined)

使用Fetch:

fetch(URLs._dashboard, {
method: "GET",
headers: {
'Content-Type': 'application/json',
"Accept": "application/json",
'Authorization': myToken,
},
signal: abortCont.signal,
}).then((response) => response.json())
.then(async (result) => {
setApiData(result); 
AsyncStorage.setItem('@code', result.code);
})
.catch((error) => {
if(error.name === 'AbortError'){
console.log('fetch aborted');
} 
});

使用Axios

axios({
method: 'get',
url: URLs._dashboard,
headers: {
'Content-Type': 'application/json',
"Accept": "application/json",
'Authorization': myToken,
}, 
signal: abortCont.signal,
}).then((response) => response.json())
.then(async (result) => { 
setApiData(result); 
AsyncStorage.setItem('@code', result.code);
})
.catch((error) => {
if(error.name === 'AbortError'){
console.log('fetch aborted');
}  
});

您不需要使用.json()解析或转换响应,因为axios响应已经是json格式的。你得到的响应是data它将有

{
// `data` is the response that was provided by the server
data: {},
// `status` is the HTTP status code from the server response
status: 200,
// `statusText` is the HTTP status message from the server response
// As of HTTP/2 status text is blank or unsupported.
// (HTTP/2 RFC: https://www.rfc-editor.org/rfc/rfc7540#section-8.1.2.4)
statusText: 'OK',
// `headers` the HTTP headers that the server responded with
// All header names are lower cased and can be accessed using the bracket notation.
// Example: `response.headers['content-type']`
headers: {},
// `config` is the config that was provided to `axios` for the request
config: {},
// `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance in the browser
request: {}
}

所有这些都可以在axios文档中找到,如果你想使用它,你应该阅读它。所以,如果你想成功,一定要养成阅读文档的习惯。

这里有更多的axios。

最新更新