微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我有 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 您可以通过在 user 函数中使用 req.query.user 来访问 controller.showSharePage

请求接受如果这有帮助...

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。