使用用户输入获取API的问题

时间:2019-11-20 13:18:47

标签: reactjs

我正在构建一个搜索表单,您可以在其中搜索城市/国家。我得到响应,但是它将localhost添加到

  

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

1 个答案:

答案 0 :(得分:2)

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

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