the*_*her 4 javascript access-token reactjs fetch-api
我遇到的问题是我有一个带有访问密钥的 API,但我不知道如何使用该 API 访问密钥在组件内设置标头。我在下面的示例中使用默认的获取随机用户 API,但我想知道应该如何以及在哪里添加带有访问密钥的标头?
import React from 'react';
export default class FetchRandomUser extends React.Component {
async componentDidMount() {
const url = "https://api.randomuser.me/"
const response = await fetch(url)
const data = await response.json();
this.setState({ person: data.results[0], loading: false })
}
render() {
return <div>
{this.state.loading || !this.state.person ? (<div>Loading...</div>) : (<div>{this.state.person.name.first}</div>)}
</div>
}
}
Run Code Online (Sandbox Code Playgroud)
fetch(url, {
method: 'GET',
headers: {
authorization: youKEY,
Accept: 'application/json',
},
});
Run Code Online (Sandbox Code Playgroud)