use*_*708 2 api json url-parameters reactjs
我只有一个页面,其中包含两个下拉列表组件;只有成功通过身份验证(有效令牌)后才能访问该页面。两个下拉列表都使用来自不同JSON-API的数据。我有一个下拉列表功能,但另一方面,它的API的URL需要参数。
示例网址: http:// buildingsAPI:111 / api / buildings /
通过带有附加ID的邮递员进行测试: http:// buildingsAPI:111 / api / buildings / abcde-abce-abc2-111-2222
样本Json:
[
{
"abc_buildingid": "1111-2222-3333-aaa-1111117",
"abc_energyprogramid": "abcde-abce-abc2-111-2222",
"siteName": "Building 1",
"Available": false,
"clientName": "Client 1"
},
{
"abc_buildingid": "222-2222-3333-aaa-1111117",
"abc_energyprogramid": "xyz11-abce-abc2-111-2222",
"siteName": "Building 2",
"Available": false,
"clientName": "Client 2"
},
]
Run Code Online (Sandbox Code Playgroud)
...已经通过用户身份验证(localStorage)获得了令牌,但是我还需要将abc_energyprogramid附加/传递为API URL的参数。
... 代码:
constructor(props) {
super(props);
this.getToken = this.getToken.bind(this);
}
componentDidMount() {
const bearerToken = this.getToken();
fetch('http://buildingsAPI:111/api/buildings/?myparam1={abc_energyprogramid}', {
method: 'GET',
headers: {
'Content-type': 'application/json',
'Authorization': `Bearer ${bearerToken}`
},
})
.then(results => results.json())
.then(buildings => this.setState({ buildings: buildings }))
}
getToken() {
return localStorage.getItem('id_token');
}
render() {
console.log(this.state.buildings);
return(
<div>
<select className="custom-select" id="siteName">
{ this.state.buildings.map(item =>(
<option key={item.siteName}>{item.siteName}</option>
))
}
</select>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
...我当前在此行代码上出现错误:“未处理的拒绝(SyntaxError):JSON输入意外结束”:.then(结果=> results.json())。请给我一些帮助吗?
我认为问题在于您的引用方式 abc_energyprogramid
更改此:
fetch('http://buildingsAPI:111/api/buildings/?myparam1={abc_energyprogramid}')
Run Code Online (Sandbox Code Playgroud)
至:
fetch(`http://buildingsAPI:111/api/buildings/?myparam1=${abc_energyprogramid}`)
Run Code Online (Sandbox Code Playgroud)
注意反引号和ES6模板字符串文字。
| 归档时间: |
|
| 查看次数: |
9761 次 |
| 最近记录: |