尝试从 URL 获取值然后在方法中使用以查找具有该值的对象

Trying to get value from URL to then use in a method to find objects with that value

我有 URL http://localhost:3000/share/user=sampleuser,它应该显示作者值与 URL 中的作者值匹配的对象。尝试调用从 URL 中获取值的函数然后在数据库中执行查找函数以查找与用户匹配的所有条目时出现错误。

    getSharedEntries(){
        const queryString = window.location.search;
        console.log(queryString);
        const urlParams = new URLSearchParams(queryString);
        const author = urlParams.get('user');
        console.log(author);
        return new Promise((resolve, reject) => {
            this.db.find({author: author}, function(err, docs){
                if(err){
                    reject(err);
                    console.log('getEntriesForLoggedInUser promise rejected');
                }else{
                    resolve(docs);
                    console.log('getEntriesForLoggedInUser promise resolved, returned', docs);
                }
            })
        })
    }
exports.showSharePage = function(req, res){
    db.getSharedEntries().then((list) => {
        res.render('share', {
            'title': 'WEIR FITNESS PLANNER',
            'sharedActivities': list,
        });
        console.log('promise resolved');
    }).catch((err)=>{
        console.log('promise rejected', err);
    })}
router.get('/share/user=:user', controller.showSharePage);
<html>
<head>
    {{>header}}
</head>

<body>
    <h1>{{title}}</h1>
    {{>sidebar}}
    <h2>Share Your Training Plan</h2>

    <input class="link" type="text" value="http://localhost:3000/share/user={{user}}" id="shareLink" readonly>
    <button class="linkButton" onclick="copyFunction()">Copy Link</button>

    <div>
        <table class="activityTable" cellspacing="0">
            <tr>
                <th>Author</th>
                <th>Week</th>
                <th>Activity</th>
                <th>Goal</th>
                <th>Completed</th>
            </tr>
            {{#sharedActivities}}
            <tr>
                <td>{{{author}}}</td>
                <td>{{{week}}}</td>
                <td>{{{name}}}</td>
                <td>{{{goal}}}</td>
                <td>{{completed}}</td>
            </tr>
            {{/sharedActivities}}
        </table>
    </div>
</body>
</div>
</html>

我对你的问题有点困惑,但我认为你在获取 URL.

user= 的值时遇到了问题

使用 Express Router 实现此目的的最简单方法是

router.get('/share', controller.showSharePage);

现在,您可以请求 get 作为 http://localhost:3000/share?user=sampleuser 您可以在 controller.showSharePage 函数

中使用 req.query.user 访问 user

如果有帮助请采纳...