多页使用relay-modern-isomorphic

时间:2018-02-01 23:09:54

标签: reactjs graphql react-relay isomorphic-relay

我遵循了这个接力 - 现代 - 同构 - 示例教程: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,同样我想添加另一个网址为localhost:3000/detailComponent的网页。但它只会向我显示localhost:3000页面。那么如何在这里进行路由,有人可以在此澄清我。

1 个答案:

答案 0 :(得分:1)

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

当您致电app.use时,您正在创建中间件,其行为与getpost等方法功能不同。 You can read the docs了解更多详细信息,但这是实际发生的事情:对于中间件(但不是getpost等),/将匹配每个路由,并且因为在您的代码中/detailComponent之前定义了中间件,即使路由为/detailComponent,它也会触发。

也就是说,如果您正在实施SSR并实现多个路由,您应该考虑将所有内容路由到Express中的一个端点,并让像React Router这样的库来处理剩下的工作。那里有很多教程,展示了如何做到这一点; here's just one