将URL参数从React发送到Node JS API

编程入门 行业动态 更新时间:2024-10-20 00:34:29

将URL参数从React<a href=https://www.elefans.com/category/jswz/34/1771348.html style=发送到Node JS API"/>

将URL参数从React发送到Node JS API

我正在使用MERN创建一个网站,并且正在努力将URL中的用户名传递给React。

我想从我通过URL传递的一位用户那里获得每篇博客文章。为此,我在find()中使用了server.js。这适用于我的NodeJS服务器http://localhost:3333/

app.get('/blog/:username', (request, reponse) => {

mongo.connect(url, function (err, db) {
    var dbo = db.db("mern-pool");
    var cherche_user = request.params.username; 
    dbo.collection("posts").find({username: cherche_user}).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        var students = result;
        reponse.send(result);
        db.close();
        });
    });
});

我需要将该数据传递到我的React blog-indiv组件中。但是,这不起作用,我的console.log(this.state)渲染了一个空数组。

当我将axios.get('http://localhost:3333/blog/:username')更改为axios.get('http://localhost:3333/blog/user123')时确实可以使用

    export default class BlogIndiv extends Component {

    constructor() {
        super();
        this.state = {
            posts: []
        };
    }

    componentDidMount() {
        axios.get('http://localhost:3333/blog/:username')
            .then(response => {
                this.setState({ posts: response.data });
                console.log(this.state);
            })
    }

    render() {
        return(
            <div>
                <h1>HE</h1>
                {this.state.posts.map(e  => {
                        return (
                            <Sub title={e.title} 
                                content={e.content}
                                author={e.username}
                            />
                        )}
                    )}
            </div>
        ) 
    }
}
回答如下:

您可以使用反引号这样传递它。

let anyvar = user123
axios.get(`http://localhost:3333/blog/${anyvar}`)

希望这能回答您的问题!编码愉快!

更多推荐

将URL参数从React发送到Node JS API

本文发布于:2024-05-07 08:20:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1755365.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:发送到   参数   React   URL   JS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!