【问题标题】:React JS - How do I pass variables (parameters) to the API URL?React JS - 如何将变量(参数)传递给 API URL?
【发布时间】:2018-10-29 12:09:51
【问题描述】:

我有一个由两个下拉列表组件组成的页面;该页面仅在成功验证(有效令牌)后才能访问。两个下拉列表都使用来自不同 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"
    },
]

...我已经在用户身份验证 (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>
        );
    }

...我目前在这行代码中收到错误:“未处理的拒绝(SyntaxError):JSON 输入的意外结束”:.then(results => results.json())。请问我能得到一些帮助吗?

【问题讨论】:

  • 我认为您的问题不在于这里,而在于您的后端。检查它是否在响应头和响应正文中返回正确的 json。
  • 你的 json 看起来更像一个数组,也许这就是问题所在?
  • abc_energyprogramid 是 JSON 文件中对象的一部分(作为字符串)。 {abc_energyprogramid} ...这是通过它的正确方法吗?
  • @Anas - 它是一个数组,客户端使用的其他 API 具有相同的设置,并且代码有效,但对于建筑物,该 API 最后需要一个参数;这是使用的两个 API 之间的唯一区别
  • @user1724708 试试这个const param = 'abc_energyprogramid' const a = http://buildingsAPI:111/api/buildings/?myparam1=${param} 从变量的开头和结尾使用反引号一个值.. 在这里不能这样做,它被视为代码跨度>

标签: json reactjs api url-parameters


【解决方案1】:

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

改变这个:

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

到:

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

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

【讨论】:

  • 如何使用 Axios 做同样的事情?
猜你喜欢
  • 2022-01-06
  • 2021-07-28
  • 2020-10-14
  • 2021-11-23
  • 2023-01-09
  • 2018-05-17
  • 2015-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多