简体   繁体   English

React JS-如何将变量(参数)传递到API URL?

[英]React JS - How do I pass variables (parameters) to the API URL?

I have a single page that consist of two dropdown-list components; 我只有一个页面,其中包含两个下拉列表组件; The page is only accessible upon successful authentication (valid token). 只有成功通过身份验证(有效令牌)后才能访问该页面。 Both dropdown-list consumes it's data from different JSON-API's. 两个下拉列表都使用来自不同JSON-API的数据。 I have one of the dropdown list functional, but for the other, the URL to it's API requires parameters. 我有一个下拉列表功能,但另一方面,它的API的URL需要参数。

Example URL : http://buildingsAPI:111/api/buildings/ 示例网址http:// buildingsAPI:111 / api / buildings /

tested via postman with an id appended : http://buildingsAPI:111/api/buildings/abcde-abce-abc2-111-2222 通过带有附加ID的邮递员进行测试http:// buildingsAPI:111 / api / buildings / abcde-abce-abc2-111-2222

sample Json: 样本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"
    },
]

...am already obtaining the token upon user authentication (localStorage), but I also need to append/pass the abc_energyprogramid as a parameter to the API URL. ...已经通过用户身份验证(localStorage)获得了令牌,但是我还需要将abc_energyprogramid附加/传递为API URL的参数。

... the code : ... 代码

     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>
        );
    }

...I currently get an error:" Unhandled Rejection (SyntaxError):unexpected end of JSON input" on this line of the code: .then(results => results.json()). ...我当前在此行代码上出现错误:“未处理的拒绝(SyntaxError):JSON输入意外结束”:.then(results => results.json())。 Could I get some help with this please? 请给我一些帮助吗?

I think the problem is the way you're referencing abc_energyprogramid 我认为问题是您引用abc_energyprogramid

Change this: 更改此:

fetch('http://buildingsAPI:111/api/buildings/?myparam1={abc_energyprogramid}')

to: 至:

fetch(`http://buildingsAPI:111/api/buildings/?myparam1=${abc_energyprogramid}`)

Notice the back-ticks and ES6 template string literal. 注意反引号和ES6模板字符串文字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM