获取URL的一部分

时间:2016-03-10 13:23:50

标签: meteor iron-router

我试图获取此网址的结尾部分(在服务器端)

http://localhost:3000/insAds/D79htZY8DQ3YmcscE

我的意思是我想得到这个字符串:

D79htZY8DQ3YmcscE

有一个类似的问题:How to get the query parameters in Iron-router?

但是没有答案对我有帮助!因为我在URL中没有查询参数。

我知道这些代码为我提供了我想要的字符串:

this.params.id

Router.current().params.id

但这些代码仅适用于客户端!我想在服务器端获取该字符串!

最后我试图获取该字符串并在此处使用:

Ads.before.insert(function(userId, doc) {
    //console.log(this.params.id);
    doc._categoryId = this.params.id;
    doc.createdAt = new Date();
    doc.createdBy = Meteor.userId();
});

1 个答案:

答案 0 :(得分:1)

您可以像这样使用Router.current().paramsthis.params

Router.route('/insAds/:id', function () {
    console.log(this.params.id); // this should log D79htZY8DQ3YmcscE in console
});

检查iron router documentation

的“快速入门”部分中的第三个示例

编辑:根据我们的聊天情况

你的钩子是

Ads.before.insert(function(userId, doc) {
    //console.log(this.params.id);
    doc._categoryId = this.params.id;
    doc.createdAt = new Date();
    doc.createdBy = Meteor.userId();
});

将其更改为

Ads.before.insert(function(userId, doc) {
    doc.createdAt = new Date();
    doc.createdBy = Meteor.userId();
});

然后像这样定义服务器中的meteor方法

Meteor.methods({
    'myInsertMethod': function (id) {
         Ads.insert({
             _categoryId: id
         });
    }
});

从客户端这样调用

Meteor.call('myInsertMethod', Router.params().id, function (err, res) { 
    console.log (err, res);
});
相关问题