先貼一下使用fetch
獲取數(shù)據(jù)的代碼:
fetch('http://localhost:3001/projects').then(async response => {
console.log(response.json())
if (response.ok) {
setList(await response.json())
}
})
通過fetch
中使用then
來獲取數(shù)據(jù)及處理response
的數(shù)據(jù)時(shí),報(bào)了Uncaught (in promise) TypeError: Failed to execute 'json' on 'Response': body stream already read
這個(gè)錯(cuò)幻件。
當(dāng)把console.log(response.json())
注釋掉之后就不再報(bào)錯(cuò),但是為什么會(huì)這樣的原因不知道嘲碱。
同時(shí)還有一個(gè)情況碌上,在這里使用了http://localhost:3001/projects
這個(gè)地址,如果把改地址改成${apiUrl}/projects
,并且這部分用反引號(hào)表示時(shí)會(huì)報(bào)鸠踪。這種方式被稱為ES6中的模板字符串绊寻。
.env 文件中
REACT_APP_API_URL=http://localhost:3001
const apiUrl = process.env.REACT_APP_API_URL