【发布时间】:2020-06-16 12:26:22
【问题描述】:
我想通过 axios.get 请求中的用户名过滤 Todo.find。问题是它没有返回任何内容 有什么建议吗?
componentDidMount() {
axios
.get("http://localhost:8080/${username}",{
// username : this.state.username
})
.then((res) => {
this.setState({todos: res.data})
console.log('--------res.data', res.data);
this.setPageCount()
})
.catch((err) => {
console.log("err", err);
});
}
app.get('/', (req, res) => {
console.log('Welcome to roffys server')
Todo.find({username:req.params.username})
.exec((err, todo) => {
if (err) {
console.log('Error retrieving todos')
} else {
console.log(req.body.username)
res.json(todo)
}
})
})
我也想从其他组件发送参数,但我不知道如何
这是改变用户名的函数,它在另一个组件中:
handleLogIn = () => {
const { username, password } = this.state
if (password.length === 0 || username.length === 0 ) {
alert('Incorrect Login!')
} else {
axios
.post(`http://localhost:8080/logIn`, {
username: username,
password: password,
})
.then((res) => {
this.setState({username: username,password: password})
localStorage.setItem('username',this.state.username)
this.props.history.push("/todoapp");
window.location.reload(false)
console.log(this.state.username)
console.log('res',res)
})
.catch((err) => {
console.log("err", err);
});
}
}
后端:
app.get('/:username', (req, res) => {
console.log('Welcome to roffys server')
Todo.find({'username': req.params.username})
.exec((err, todo) => {
if (err) {
console.log('Error retrieving todos')
} else {
res.json(todo)
}
})
})
【问题讨论】:
-
我已经更新了我的答案,加入了一种转移用户名的方式。
标签: node.js reactjs mongodb mongoose