javascript - 获取对我的 React 应用程序的 API 请求
问题描述
我正在尝试调用 API 以在 React.js 中显示我的网站上的信息,API 需要读取令牌,但我不知道我必须做什么才能生成令牌,因为我的应用程序没有需要任何注册或登录。它就像一个产品目录,您可以对其进行个性化设置。我不太了解这个,因为我是新手,我自己在学习,所以很抱歉,如果这令人困惑,请随时提出任何问题,我会尽力回答:)
这是我到目前为止的代码:
export class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
models: [],
isLoaded: false
};
}
componentDidMount() {
fetch(myUrlAPI)
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
models: json
});
});
}
render() {
const { isLoaded, models } = this.state;
if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div>
<ul>{models.map(model => <li>{model.name}</li>)};</ul>
<a href="/sofa">
<div className="Parcelas">
<img
src="../../img/image-card-1@2x.png"
className="ParcImage"
alt="sofa"
/>
<h1>Sofa hipnos</h1>
<h2>
1,200<span>€</span>
</h2>
<p className="Features">
w 20.5 x 15.5 x h 19.5 (cm)<br />Pele
</p>
<button className="Botao">
<p className="MostraDepois">See Details</p>
<span>+</span>
</button>
<img
src="../../img/points.svg"
className="Decoration"
alt="points"
/>
</div>
</a>
</div>
);
}
}
}
在<ul>
标签中,我只是想测试json的结果。
另外,每次我.map
用来制作数组时,都会收到此错误(TypeError: models.map is not a function
)或类似错误,您能告诉我为什么吗?
解决方案
尝试这种方式,对于令牌,您需要与后端开发人员确认您应该发送的方式和内容。
let token = '1234567';
fetch(myUrlAPI, {
method: "GET",
headers: {
"authorization-key": token
}
}).then(res => res.json()
).then(function(json) {
this.setState({
isLoaded: true,
models: json
});
}, function(error) {
console.log(error)
})
推荐阅读
- sql - 多个表上的 SQL 层次结构并导致多行(不是 JOINING)
- c# - 无法从 xamarin.forms 将 ResourceDictionary 添加到 Application.Current.Resources.MergedDictionaries
- javascript - 如何在柏树中上传图片?
- symfony4 - 如何在 Symfony 项目中安装 Mercure?
- visual-c++ - 为 CListBox 太宽的项目显示工具提示
- c# - Rider 找不到已安装的 .NET Core,无法使用 MSBuild.dll 访问目录
- css - 无法使用优化的字体作为 CSS 内容
- android - 在构建应用程序时收到关于我的 Kotlin 版本的警告
- angular - 如何在 Excel 中安装使用 Angular 制作的 Addin Excel
- docker - dpkg 在 ubuntu-docker arm64 上安装错误