最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

网站源码admin16浏览0评论

将URL参数从React发送到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}`)

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

发布评论

评论列表(0)

  1. 暂无评论