reactjs - 使用用户输入获取 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>
)
}
解决方案
只需http/https
在链接前添加协议:
const endpoint = `https://${api}q=${this.state.text}&username=${userName}`;
推荐阅读
- javascript - 如何循环对象数组以根据另一个字符串数组过滤掉
- python-3.x - 字典到 csv 只会产生不完整/不正确的数据
- android - Xposed - 我可以打印内部类方法,但方法挂钩不起作用
- reactjs - React Hook useState 构造函数与 Asyncstorage
- php - 在 WooCommerce 中购买产品后,将相关订单 ID 添加为用户元数据
- android - 获取 gpx 轨道的界限
- windows-server-2012 - 在 windows server 2016 中是否兼容 Visual source safe 2005
- mobile - wso2 安装按钮在移动应用程序管理上不起作用
- python - 如何设置文件缓冲参数?
- javascript - 尝试在 React 中将新元素添加到数组状态时出错