提问者:小点点

使用参数筛选GET请求


我想过滤TODO.Find by username from AXIOS.GET请求。问题是它没有返回任何建议?

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

})

共2个答案

匿名用户

应该是:

`http://localhost:8080/${username}`

“http://localhost:8080/${username}”

匿名用户

您不正确地使用了模板文字,应该如下所示:

.get(`http://localhost:8080/${username}`)

你不应该接受一个动态参数吗? 像这样:

app.get('/:username',(req,res)=>{//。。。

更新:

关于将用户名传输到其他组件,您可以这样做:

this.props.history.push({
  pathname: '/todoapp',
  state: { username: this.state.username }
}) 

在todo组件中:

componentDidMount() {
    axios
        .get(`http://localhost:8080/${this.props.location.state.username}`)