reactjs - 使用用户输入获取 API 时出现问题

标签 reactjs

我正在构建一个搜索表单,您可以在其中搜索城市/国家。我收到响应,但它将 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>
    )
  }

最佳答案

只需在链接前添加 http/https 协议(protocol)即可:

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

关于reactjs - 使用用户输入获取 API 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58955326/

相关文章:

javascript - publicPath 与 react 热加载器

javascript - 如何获取元素的值以便在新元素中打印它们?

reactjs - redux 和 immutable.js : putting non-serializable objects into state

reactjs - firebase onSnapshot 函数无限循环正常吗?

javascript - 使用React,想要修复useEffect缺少依赖项错误

javascript - 状态无法访问 Prop

javascript - react 显示子组件值的总和不准确

javascript - 为什么即使 webpack 没有抛出任何错误,React 组件也不会渲染?

node.js - 使用 Multer 进行 React Hooks 和 Axios 图像上传

reactjs - React 服务器端获取(异步渲染)