我目前正在使用Express在React.js和react-router中加载一个单页客户端应用程序。
它的结构使得我有/关于和/联系作为标准的玉视图,但/ ui作为实际的反应应用程序。任何超出/ ui的后续导航(例如ui / dashboard)都由react-router处理。这意味着如果我需要访问www.foobar.com/ui/dashboard,我需要点击我的ui *路线,抓住url过去ui /(在这种情况下是仪表板)并将其传递给路由器(通过变量)在玉视图中,它是反应应用程序的入口点,然后从反应组件加载此路径。我想使这种方法工作,因为这使用户能够为反应应用程序保存网址。麻烦的是,我无法弄清楚它是如何工作的:
代码:
//Example 1
router.get('/ui*', requireLogin, function(req, res){
res.render('./app/index', {initURL: req.path); //Doesnt work as everything past ui/ is still present when react-router does its thing
});
//Example 2
router.get('/ui', requireLogin, function(req, res){
res.render('./app/index', {initURL: req.path); //Doesnt work as no way of accessing the initial requests url when redirecting
});
router.get('/ui*', requireLogin, function(req, res){
res.redirect('/ui'); //Cant pass additional parameters here
});
答案 0 :(得分:1)
var express = require('express')
var React = require('react')
var Router = require('react-router')
var routes = require('./routes')
var app = express()
app.use('/ui', requireLogin, function(req, res, next) {
// store initially requested url as a query parameter
// e.g. /ui/dashboard would become /ui?redirect=dashboard
// if the user is not logged in
var params = req.query;
// params.redirect === 'dashboard'
// Now you can check if there is a redirect and use it in your initial route
var router = Router.create({location: req.url, routes: routes})
router.run(function(Handler, state) {
var html = React.renderToString(<Handler/>, {initalState: params.redirect})
return res.render('react_page', {html: html})
})
})
这会让你走上正轨吗?
答案 1 :(得分:0)
我认为您必须区分客户端路由和服务器端路由。
您需要服务器端路由:
您还需要一个客户端路由框架(如用于angular.js的ui.router):
问候,雷米