在服务器端使用Passport-jwt呈现Express / React应用程序

我有一个使用react-router的通用NodeJS,Express,React / Redux应用程序。 它从服务器端在应用程序的初始请求和客户端上对来自react-router的后续请求进行渲染。

我的routes.js文件:

<Route path="/" component={App}> <Route path="/main" component={Main}/> <Route path="/login" component={Login}/> </Route> 

我有一个通配符高速路由匹配这个反应路线,并发送组件标记回模板:

 import routes from '../routes'; app.get('*', (req, res) => { match( { routes, location: req.url }, (err, redirectLocation, renderProps) => { let markup; if (renderProps) { markup = renderToString( <Provider store={store}> <RouterContext {...renderProps}/> </Provider> ); } else { markup = renderToString(<NotFoundPage/>); res.status(404); } return res.render('index', { markup }); } ); }); 

现在我想用passport-jwt来保护被通配符路由拦截的一些路由,例如:

 app.get("*", passport.authenticate('jwt', { session: false }), (req, res) => { match( { routes, location: req.url }, (err, redirectLocation, renderProps) => { res.json("Success! You can not see this without a token"); } ) }); 

如何在通配符路由中只保护routes.js中的给定路由?

你可以通过app.use添加一些中间件来做到这app.use 。 ( https://expressjs.com/en/4x/api.html#app.use

只要确保在通配符处理程序之前调用它

 app.use("/main", passport.authenticate('jwt', { session: false }), function(req, res){ res.json("Success! You can not see this without a token"); });