【发布时间】:2021-01-10 21:36:46
【问题描述】:
我正在使用 django 后端和 react 前端构建我的第一个 Web 应用程序。
我无法获取数据并将它们作为输出打印到我的页面上。 我不知道为什么可以从https://jsonplaceholder.typicode.com/todos 之类的网站获取虚拟 api 数据,但我自己的 api 数据却不行。
这是一个小代码 sn-p,我在 HTML-Inspector 中得到错误: JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符
const [todos, setTodos] = React.useState([]);
const url = "http://127.0.0.1:8000/article/";
const proxyurl = "https://boiling-tor-92690.herokuapp.com/";
React.useEffect(() => {
fetch(proxyurl + url,{
method:'GET',
headers:{
'Content-Type':'application/json'
}
})
.then(res => res.json())
.then(todos => setTodos(todos))
.catch(err => console.log(err.message));
}, []);
return (
<div>
{todos.map(e =>{
return <h2>{e.email}</h2>
})}
</div>
);
这里我不得不使用 heroku-proxy 来修复 CORS 错误
我还尝试了一个功能组件,并且可以在我的控制台中获取我的 API 数据,但我仍然收到 JSON 解析错误:
componentDidMount() {
var self = this;
fetch('http://127.0.0.1:8000/article/')
.then(function(response) {
return response.json()
})
.then(function(data) {
self.setState({
data
},
() =>
console.log(self.state));
});
}
有人知道如何解决这个问题吗?
【问题讨论】:
-
如果您检查您尝试获取的资源,您会发现 JSON 未正确关闭。使用不同的资源。
标签: javascript json reactjs api