React JS 使用 axios.get(url) 和 param 从数据库中获取数据



我正在尝试使用 React 中的 axios 从数据库中获取数据。 不幸的是,由于某种原因,我使用的 url 不返回数据,尽管在浏览器中它返回了数据。url 包含一个参数,这很可能是一个问题,因为当我使用没有参数的 url 时,会返回数据。

constructor(props) {
super(props);
this.state = {
userId : this.props.match.params.userId,
users:[]
}
}
componentDidMount() {
const url = "http://localhost:8080/getUser?userId=1";
axios.get("http://localhost:8080/getUser", {params: {
userId: this.state.userId
}})
.then(response => response.data)
.then((data) => {
this.setState({users: data})
});
console.log(this.state.users);
}

有谁知道如何使用 REST API 和 axios 正确获取数据库数据?

axios.get("http://localhost:8080/getUser", {
params: {
userId: this.state.userId
}
})
.then(response => response.json()) // You need to parse JSON
.then((data) => {
this.setState({users: data})
});

唯一的区别在于首先,您需要将数据解析为 JSON。

最新更新