使用 relay-modern-isomorphic 的多个页面

Multiple pages using relay-modern-isomorphic

我遵循了这个 relay-modern-isomorphic-example 教程:Link

在该教程中,他们有一个没有路由的页面,

import express from 'express';
import graphQLHTTP from 'express-graphql';
import nunjucks from 'nunjucks';
import path from 'path';
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import {schema} from './data/schema';
import renderServer from './js/renderServer';
import renderServer2 from './js/renderServer2';
const APP_PORT = 3000;
const GRAPHQL_PORT = 8080;

// Expose a GraphQL endpoint
const graphQLServer = express();
graphQLServer.use('/', graphQLHTTP({schema, pretty: true}));
graphQLServer.listen(GRAPHQL_PORT, () => console.log(
  `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}`
));

// Serve the Relay app
const compiler = webpack({
  entry: path.resolve(__dirname, 'js', 'app.js'),
  module: {
    loaders: [
      {
        exclude: /node_modules/,
        loader: 'babel',
        test: /\.js$/,
      },
    ],
  },
  output: {filename: 'app.js', path: '/'},
  devtool: 'source-map'
});

const app = new WebpackDevServer(compiler, {
  contentBase: '/public/',
  proxy: {'/graphql': `http://localhost:${GRAPHQL_PORT}`},
  publicPath: '/js/',
  stats: {colors: true},
});

nunjucks.configure('views', {autoescape: true});

// Serve static resources
app.use('/public', express.static(path.resolve(__dirname, 'public')));
app.use('/', renderServer);
app.use('/detailComponent', renderServer2);
app.listen(APP_PORT, () => {
  console.log(`App is now running on http://localhost:${APP_PORT}`);
});

在上面的代码中,默认情况下它位于 localhost:3000,同样我想添加另一个带有 url localhost:3000/detailComponent 的页面。但它只会向我显示 localhost:3000 页面。那么这里如何进行路由,有人可以解释一下吗。

您需要调换两条路线的顺序。

当您调用 app.use 时,您正在创建中间件,它的行为不同于 getpost 等方法函数。 You can read the docs 了解更多详细信息,但这是有效发生的事情:对于中间件(但不是 getpost 等)/ 将匹配 每个 路由,并且因为该中间件是在代码中的 /detailComponent 之前定义的,所以即使路由是 /detailComponent.

它也会触发

就是说,如果您正在实施 SSR 并实施多个路由,您可能应该考虑将所有内容路由到 express 中的一个端点,然后让像 React Router 这样的库来处理其余部分。那里有很多教程展示了如何做到这一点; here's just one.