【问题标题】:filter GET request with params使用参数过滤 GET 请求
【发布时间】: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


【解决方案1】:

应该是:

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

不是"http://localhost:8080/${username}"

【讨论】:

    【解决方案2】:

    你错误地使用了模板字面量,应该如下:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-23
      • 1970-01-01
      • 1970-01-01
      • 2019-11-07
      • 2010-11-27
      • 2020-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多