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

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

我有一个包含两个下拉列表组件的页面;该页面只有在身份验证成功(有效令牌)后才能访问。两个下拉列表都使用来自不同 JSON-API 的数据。我有一个下拉列表功能,但对于另一个,URL 到它的 API 需要参数。

示例URLhttp://buildingsAPI:111/api/buildings/

通过邮递员测试并附加了 idhttp://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"
    },
]

...我已经在用户身份验证(localStorage)时获得令牌,但我还需要 append/pass abc_energyprogramid 作为 API [=45= 的参数].

...代码:

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

...我目前收到一个错误:“Unhandled Rejection (SyntaxError):unexpected end of JSON input” 在这行代码中:.then(results => results.json( )).请问我可以得到一些帮助吗?

我认为问题在于您引用的方式 abc_energyprogramid

改变这个:

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

至:

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

注意反引号和 ES6 模板字符串文字。