Iron Router和Meteor中的服务器端路由 [英] Server side routes in Iron Router and Meteor

查看:137
本文介绍了Iron Router和Meteor中的服务器端路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

向前



看起来在Meteor中,我们无法调用服务器端路由来将文件呈现到页面,而没有从我们的正常工作流程中解决问题,从我所阅读的有关服务器端路由。我希望我错了这个,有一个简单的方法来实现我想要做的...



**对不起,如果这是一个长的,但我认为在这种情况下提供更多的背景和上下文保证**



软件/版本



使用最新的Iron Router 1. *和Meteor 1. *开始,我只是使用accounts-password。



背景/上下文



我有一个onBeforeAction,根据用户是否登录,将用户重定向到欢迎页面或主页:



both / routes.js

  Router.onBeforeAction(function {){
if(!Meteor。 user()|| Meteor.loggingIn())
this.redirect('welcome.view');
else
this.next();
}
,{except:'welcome.view'}
);

Router.onBeforeAction(function(){
if(Meteor.user())
this.redirect('home.view');
else
this.next();
}
,{only:'welcome.view'}
);

在同一个文件中,/ routes.js,我有一个简单的服务器端路由, pdf到屏幕,如果我删除onBeforeAction代码,路由工作(pdf呈现到页面):

 路由器.route('/ pdf-server',function(){
var filePath = process.env.PWD +/server/.files/users/test.pdf;
console.log(filePath );
var fs = Npm.require('fs');
var data = fs.readFileSync(filePath);
this.response.write(data);
.response.end();
},{其中:'server'});



在服务器路由上抛出异常



旁边的点,但我得到一个例外,当我添加上述服务器端路由到文件,并采取路由/ pdf-server,同时保持onBeforeAction代码。



了解异常情况,请点击此处: SO异常问题



异常的解决方案



上述SO问题的答案的主要要点是你在你的Route.onBeforeAction中使用Meteor.user(),但它没有访问这个信息,当, / POST请求 [服务器端路由?],到服务器,它没有任何关于用户的认证状态的信息。 / p>

根据相同的SO回答者的解决方案是找到一种验证用户的替代方法,一个方法是使用cookies'



另一个SO回答(通过与之前相同的回答者),其中设置和获取cookie的方法在此概述: SO Cookie技术



**因此,为了总结,为了允许服务器端路由,我使用cookie,而不是像Meteor.userId()或this.userId。 **



Cookie相关代码已添加



所以我在项目中添加了以下代码:
client / main.js

  Deps.autorun(function(){
if(Accounts.loginServicesConfigured()& & Meteor.userId()){
setCookie(meteor_userid,Meteor.userId(),30);
setCookie(meteor_logintoken,localStorage.getItem(Meteor.loginToken),30 );
}
});

在我的服务器端路由中,我将路由更改为:



both / routes.js

  Router.route('/ pdf-server',function {
//使用get_cookies函数解析cookies:http://stackoverflow.com/questions/3393854/get-and-set-a-single-cookie-with-node-js-http-server
var userId = get_cookies(req)['meteor_usserid'];
var loginToken = get_cookies(req)['meteor_logintoken'];
var user = Meteor.users.findOne({_ id:userId, services.resume.loginTokens.token:loginToken});
var loggedInUser =(user)?user.username:未登录;

var filePath = process.env.PWD +/server/.files/users/test.pdf;
console.log(filePath);
var fs = Npm.require('fs');
var data = fs .readFileSync(filePath);
this.response.write(data);
this.response.end();
},{其中:'server'});

但这不能按预期工作,setCookie代码由于某种原因无效。



我的问题




问题1:按照
SO Cookie技术似乎没有为我工作,这是
技术仍然在15年工作?



问题2:使用cookie,如何通知服务器
基于这些cookie的身份验证状态?或者,另一种方式,如何添加cookie检查在我的服务器
侧路由通知服务器关于用户?我可以检查
什么东西在这条路线真的;我可以拒绝任何用户,但不知何故
服务器需要知道有关登录的用户?



问题3:Cookie是最好的方式或者有一个
更简单的方法来实现同样的事情吗?



边问题:我见过几个地方使用中间件对于
服务器端路由,例如:




  WebApp.connectHandlers.stack。拼接(...); 

WebApp.connectHandlers.use(function(...)...);




但这些示例都没有安全内​​部,



解决方案

侧路由正在运行全局 onBeforeAction 代码(它在共享目录中定义),因为服务器路由是不理解用户认证信息的简单REST端点 Meteor.user()不工作)。解决方案是用 Meteor.isClient 包装客户特定 onBeforeAction 调用,或者简单地将该代码移动到 client 目录。例如:

  if(Meteor.isClient){
Router.onBeforeAction(function(){
if(!Meteor.user()|| Meteor.loggingIn())
this.redirect('welcome.view');
else
this.next();
}
,{except:'welcome.view'}
);

Router.onBeforeAction(function(){
if(Meteor.user())
this.redirect('home.view');
else
this.next();
}
,{only:'welcome.view'}
);
}

Router.route('/ pdf-server',function(){
...
},{其中:'server'});


Forward

It seems that in Meteor, we cannot call a server side route to render a file to the page without some sort of work-around from our normal workflow, from what I've read about server side routes. I hope I'm wrong about this, and there's a simple way to achieve what I'm looking to do...

** Sorry if this is a little long, but I think in this case providing more background and context is warranted **

Software/Versions

I'm using the latest Iron Router 1.* and Meteor 1.* and to begin, I'm just using accounts-password.

Background/Context

I have an onBeforeAction that simply redirects the user to either the welcome page or home page base upon if the user is logged in or not:

both/routes.js

Router.onBeforeAction(function () {
  if (!Meteor.user() || Meteor.loggingIn())
    this.redirect('welcome.view');
  else
    this.next();
  }
  ,{except: 'welcome.view'}
);

Router.onBeforeAction(function () {
  if (Meteor.user())
    this.redirect('home.view');
  else
    this.next();
  }
  ,{only: 'welcome.view'}
);

In the same file, both/routes.js, I have a simple server side route that renders a pdf to the screen, and if I remove the onBeforeAction code, the route works (the pdf renders to the page):

Router.route('/pdf-server', function() {
  var filePath = process.env.PWD + "/server/.files/users/test.pdf";
  console.log(filePath);
  var fs = Npm.require('fs');
  var data = fs.readFileSync(filePath);
  this.response.write(data);
  this.response.end();
}, {where: 'server'});

Exception thrown on Server Route

It's beside the point, but I get an exception when I add the above server side route to the file and take the route /pdf-server, while keeping the onBeforeAction code in place.

Insights into the exception can be found here: SO Question on Exception

Solution to the Exception

The main gist of the answer in the SO Question above is "You use Meteor.user() in your Route.onBeforeAction but it has no access to this information", and when, "your browser make a GET/POST request" [Server side route?], "to the server it doesn't have any information regarding the user's authentication state."

The solution, according to the same SO answerer is to "find an alternative way to authenticate the user," and one way to do this is to use "cookies'".

So, following up on this, I found another SO answer (by the same answerer as before), where a method to set and get the cookies is outlined here: SO Cookies technique

** So, to summarize, in order to allow for server side routes, it is suggested I use cookies instead of something like Meteor.userId() or this.userId. **

Cookie related code added

So I added the following code to my project: client/main.js

Deps.autorun(function() {
    if(Accounts.loginServicesConfigured() && Meteor.userId()) {
        setCookie("meteor_userid",Meteor.userId(),30);
        setCookie("meteor_logintoken",localStorage.getItem("Meteor.loginToken"),30);
    }
}); 

In my server side route, I changed the route to this:

both/routes.js

Router.route('/pdf-server', function() {
  //Parse cookies using get_cookies function from : http://stackoverflow.com/questions/3393854/get-and-set-a-single-cookie-with-node-js-http-server
  var userId = get_cookies(req)['meteor_usserid'];
  var loginToken = get_cookies(req)['meteor_logintoken'];
  var user = Meteor.users.findOne({_id:userId, "services.resume.loginTokens.token":loginToken});
  var loggedInUser = (user)?user.username : "Not logged in";

  var filePath = process.env.PWD + "/server/.files/users/test.pdf";
  console.log(filePath);
  var fs = Npm.require('fs');
  var data = fs.readFileSync(filePath);
  this.response.write(data);
  this.response.end();
}, {where: 'server'});

But this does not work as expected, the setCookie code is not valid for some reason.

My Questions

Question 1: Setting/getting the cookies in the manner depicted in the SO Cookies technique doesn't seem to work for me, does this technique still work in '15?

Question 2: Using cookies, how do I inform the server of the authentication state based on these cookies? Or, another way, How does adding the cookie check in my server side route "inform" the server about the user? I could check for anything in this route really; I could reject any user, but somehow the server needs to "know" about the user logged in right?

Question 3: Is cookies the best way to go about this, or is there a simpler way to achieve the same thing?

Side Question: I've seen a few places where middle ware is used for server side routes, for example:

WebApp.connectHandlers.stack.splice(...);

WebApp.connectHandlers.use(function(...) ...);

But none of these examples had security inside, will using middle ware in this way allow me to get around my problem?

解决方案

Your server-side routes are running the global onBeforeAction code (it's defined in a shared directory), which breaks because the server routes are simple REST endpoints which don't understand user authentication information (i.e. Meteor.user() doesn't work). The solution is to wrap the client-specific onBeforeAction calls with Meteor.isClient or simply move that code under the client directory. For example:

if (Meteor.isClient) {
  Router.onBeforeAction(function () {
    if (!Meteor.user() || Meteor.loggingIn())
      this.redirect('welcome.view');
    else
      this.next();
    }
    ,{except: 'welcome.view'}
  );

  Router.onBeforeAction(function () {
    if (Meteor.user())
      this.redirect('home.view');
    else
      this.next();
    }
    ,{only: 'welcome.view'}
  );
}

Router.route('/pdf-server', function() {
  ...
}, {where: 'server'});

这篇关于Iron Router和Meteor中的服务器端路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆