admin管理员组文章数量:1293150
The problem I'm struggling with is I have an API with an access key and I don't know how to setup the header inside the ponent with that API access key. I'm using a default fetch random user API in example below but I want to know how and where should I add that header with access key?
import React from 'react';
export default class FetchRandomUser extends React.Component {
async ponentDidMount() {
const url = "/"
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>
}
}
The problem I'm struggling with is I have an API with an access key and I don't know how to setup the header inside the ponent with that API access key. I'm using a default fetch random user API in example below but I want to know how and where should I add that header with access key?
import React from 'react';
export default class FetchRandomUser extends React.Component {
async ponentDidMount() {
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>
}
}
Share
edited Aug 4, 2023 at 16:19
Brian Tompsett - 汤莱恩
5,89372 gold badges61 silver badges133 bronze badges
asked Feb 23, 2020 at 6:45
the preacherthe preacher
3773 gold badges8 silver badges26 bronze badges
2 Answers
Reset to default 5fetch(url, {
method: 'GET',
headers: {
authorization: youKEY,
Accept: 'application/json',
},
});
This is how you can pass your api key in url https://randomapi./api/qcol88t8?key=TCGJ-8B0M-33L6-UX5Q
;`
Code
export default class FetchRandomUser extends React.Component {
state = {
loading: true,
person: {}
};
async ponentDidMount() {
const url = `https://randomapi./api/qcol88t8?key=TCGJ-8B0M-33L6-UX5Q`;
const response = await fetch(url);
const data = await response.json();
this.setState({ person: data.info, loading: false });
}
render() {
return (
<div>
{this.state.loading || !this.state.person ? (
<div>Loading...</div>
) : (
<h2>{this.state.person.user.username}</h2>
)}
</div>
);
}
}
本文标签: javascriptSet header in react API request in componentDidMount()Stack Overflow
版权声明:本文标题:javascript - Set header in react API request in componentDidMount() - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741574049a2386179.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论