首页 > 解决方案 > 如何修复来自'this.props.match.params.id'的axios错误未定义错误的get方法

问题描述

我正在开发 Web 应用程序的前端和后端。为此,我使用了 mongo、express、reactjs 和 node 技术。我为 get、post、put delete 开发 API,并通过 postmon 对其进行测试。有用 !但是当我将它连接到前端时,我的 get 方法不起作用。此 get 方法意味着获取特定对象。

这是我的 api 获取方法,

// get a book by id
book_route.route('/:id').get(function (req, res) {
    let id = req.params.id;
    Book.findById(id, function (err, book){
        if(err){
            console.log(err);
        }
        else {
            res.json(book);
        }
    });
});

请注意,这是通过 postmon 工作的,例如,它检索了一个具有其 id 的对象。

http://localhost:4000/book/5cbcc159e4db244de040e854

它检索到以下 JSON 对象。

{
    "_id": "5cbcc159e4db244de040e854",
    "title": "Miracles from heaven",
    "isbn_no": "439564969",
    "author": "Jense Bend",
    "published_year": 2015,
    "no_of_copies": 34,
    "public_or_rare": "",
    "__v": 0
}

我想将以上 JSON 对象值加载到我的表单元素中。所以我在前端尝试了这个,如下所示,

  componentDidMount() {

        axios.get('http://localhost:4000/book/'+this.props.match.params.id)
        //axios.get('http://localhost:4000/book/5cbcc159e4db244de040e854')
            .then(response => {
               // console.log(this.props.match.params.id);
                this.setState({
                    title: response.data.title,
                    isbn_no: response.data.isbn_no,
                    author: response.data.author,
                    published_year: response.data.published_year,
                    no_of_copies: response.data.no_of_copies,
                    public_or_rare: response.data.public_or_rare
                 });
            })
            .catch(function (error) {
                console.log(error);
            })
    }

注意,要检查这一点,我评论第一行并取消评论axios.get('http://localhost:4000/book/5cbcc159e4db244de040e854')这一行。它显示带有值的表单元素。

但是这条线不起作用,axios.get('http://localhost:4000/book/'+this.props.match.params.id)

最后我想将值加载到我的表单中。我在前端编写了其他 onchange 函数。请注意,当我启用此行时,这些已正确呈现axios.get('http://localhost:4000/book/5cbcc159e4db244de040e854')

这里有什么问题吗,请大家帮我解决这个问题。

标签: reactjsrestgetaxios

解决方案


推荐阅读