首页 > 解决方案 > 使用用户输入获取 API 的问题

问题描述

我正在构建一个搜索表单,您可以在其中搜索城市/国家。我收到了回复,但它会将 localhost 添加到 url

http://localhost:3000/api.geonames.org/searchJSON?q=london&username=username

它不应该做什么......我做错了什么?

state = {
            text: ""
          }



 handleChange = (e) => {
    this.setState({
      [e.target.name]: e.target.value
    })
  }



componentDidMount() {
    const endpoint = `${api}q=${this.state.text}&username=${userName}`
    console.log(endpoint)
    fetch(endpoint)
    .then(res => {
      console.log(res)
    })
  }



handleSubmit = (e) => {
    e.preventDefault()
    this.setState({text: ""})

    this.componentDidMount()

  }



 render() {
    return (
      <div>
        <h1>CityPop</h1>
        <form onSubmit={this.handleSubmit}>
          <h3>Search by city</h3>
          <input
            type="search"
            name="text"
            value={this.state.text}
            onChange={this.handleChange}
          />
          <button>Search city</button>
        </form>
      </div>
    )
  }

标签: reactjs

解决方案


只需http/https在链接前添加协议:

const endpoint = `https://${api}q=${this.state.text}&username=${userName}`;

推荐阅读