[英]How to return a response from a fetch in javascript
我在 React Native 項目中返回 API 調用的響應時遇到問題。
let response = fetch('http://3.133.123.120:8000/auth/token', {
method: "POST",
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
client_id: 'NTMtzF7gzZPU9Ka35UFsDHvpR8e4D1Fy4OPRsurx',
grant_type: 'password',
username: user,
password: pass,
})
})
.then((response) => response.json())
.then((response) => this.setState({jsonData: response}))
.then(() => alert('resposne jsonData: ' + JSON.stringify(this.state)));
alert('resposne jsonData: ' + JSON.stringify(response))
上面的代碼在底部的 .then() 語句中返回正確的響應,但是,我無法使用 fetch() 語句之外的數據。
我嘗試在 fetch() 之外使用的任何東西(比如我在底線中的警報)都給了我以下...
{"_40":0,"_65":0,_55":null,"_72":null}
另請注意,這一切都在 React 類組件中
fetch
返回一個Promise
: https : //developer.mozilla.org/en-US/docs/Web/API/Fetch_API
你已經可以訪問那個 final 中的值了。 如果您正在尋找一種在不使用回調的情況下使用以下值的方法,您可以考慮使用async/await
樣式並將此代碼包裝在一個函數中,如下所示:
const fetchData = async () => { const results = await fetch() // put your fetch here alert(results.json()); };
獲取信息: https : //developer.mozilla.org/en-US/docs/Web/API/Fetch_API
異步/等待信息: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.