我一直在尝试创建一个 React 站点,它会从 API 获取 GET 响应并将其打印到我的 .html 文件中。我已经成功地正确获取了文件,但无法访问服务器发送给我的 JSON 数据。
如果我在 Fetch 请求中使用 no-cors,我会得到一个几乎不包含任何内容的不透明响应,但如果我转到开发人员工具,我可以在那里找到我的数据并读取它。如果我确实使用 cors,几乎同样的事情。我收到 403 错误,但我的数据位于浏览器内存中,但我的代码未将其打印出来。我可以在开发者工具中找到网络的回复。
为什么服务器给我一个错误,但我仍然得到我的数据?如果它在浏览器中,我该如何访问它?
class Clock extends React.Component {
constructor(props) {
super(props)
this.state = {data2: []}
this.apihaku = this.apihaku.bind(this)
}
componentDidMount() {
this.apihaku(),
console.log("Hei")
}
apihaku () {
fetch('https://#######/mapi/profile/',
{method: 'GET', mode:'no-cors', credentials: 'include',
headers: {Accept: 'application/json'}}
).then((response) => {
console.log(response);
response.json().then((data) =>{
console.log(data);
});
});
}
render() {
return <div>
<button>Button</button>
</div>
}}
ReactDOM.render(
<Clock />,
document.getElementById('content')
)
Run Code Online (Sandbox Code Playgroud)
编辑:尝试建议后出现错误图像
https://i.stack.imgur.com/wp693.png
试试这个,看看错误发生在哪里我相信解析,但让我们检查一下
fetch(https://#######/mapi/profile/, {
method: "GET",
headers: {
"Content-Type": "application/json"
},
credentials: "include"
})
.then((response) => {
console.log(response);
try {
JSON.parse(response)
}
catch(err){
console.log("parsing err ",err)
}
})
.catch((err)=>{
console.log("err ",err)
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19253 次 |
| 最近记录: |