在服务器ReactDOMServer.renderToString和StaticRouter上提供React应用程序

时间:2017-11-22 09:44:41

标签: reactjs react-router

我正在尝试从服务器快速渲染我的反应应用程序,但它给我一个错误:

throw err;
      ^

SyntaxError: /Users/f/Documents/GitHub/my-app/server/app.js: Unexpected token (34:6)
  32 |   const context = {};
  33 |   const markup = ReactDOMServer.renderToString(
> 34 |       <StaticRouter location={req.url} context={context}>
     |       ^
  35 |         <App />
  36 |       </StaticRouter>
  37 |   );
    at Parser.pp$5.raise (/Users/f/Documents/GitHub/my-app/node_modules/babylon/lib/index.js:4454:13)
    at Parser.pp.unexpected (/Users/f/Documents/GitHub/my-app/node_modules/babylon/lib/index.js:1761:8)
    at Parser.pp$3.parseExprAtom (/Users/f/Documents/GitHub/my-app/node_modules/babylon/lib/index.js:3750:12)
    at Parser.pp$3.parseExprSubscripts (/Users/f/Documents/GitHub/my-app/node_modules/babylon/lib/index.js:3494:19)
    at Parser.pp$3.parseMaybeUnary (/Users/f/Documents/GitHub/my-app/node_modules/babylon/lib/index.js:3474:19)
    at Parser.pp$3.parseExprOps (/Users/f/Documents/GitHub/my-app/node_modules/babylon/lib/index.js:3404:19)
    at Parser.pp$3.parseMaybeConditional (/Users/f/Documents/GitHub/my-app/node_modules/babylon/lib/index.js:3381:19)
    at Parser.pp$3.parseMaybeAssign (/Users/f/Documents/GitHub/my-app/node_modules/babylon/lib/index.js:3344:19)
    at Parser.pp$3.parseExprListItem (/Users/f/Documents/GitHub/my-app/node_modules/babylon/lib/index.js:4312:16)
    at Parser.pp$3.parseCallExpressionArguments (/Users/f/Documents/GitHub/my-app/node_modules/babylon/lib/index.js:3573:20)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

// server.js

// server/app.js
import path from 'path';
import express from 'express';
import morgan from 'morgan';
import React from 'react';
const ReactDOMServer = require('react-dom/server');
import { StaticRouter } from 'react-router-dom';
import { App } from '../src/App';
const app = express();

// Setup logger
app.use(morgan(
    ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] :response-time ms'));
// use ejs templates
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// Serve static assets
app.use(express.static(path.resolve(__dirname, '..', 'build')));

// Always return the main index.html, so react-router render the route in the client
// app.get('*', (req, res) => {
//   console.log('hi from app.get');
//
//   res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
// });



// universal routing and rendering
app.get('*', (req, res) => {
  const context = {};
  const markup = ReactDOMServer.renderToString(
      <StaticRouter location={req.url} context={context}>
        <App />
      </StaticRouter>
  );

  // context.url will contain the URL to redirect to if a <Redirect> was used
  if (context.url) {
    return res.redirect(302, context.url);
  }

  // TODO manage 404
  const status = context.matchedRoutes.page.is404 ? 404 : 200;
  return res.status(status).render('index', { markup });
});



module.exports = app;

和我的应用

export const App = () => (
    <div className="App">
      <Helmet title="You Are Doing Great" />
      <Header />
      <Routes />
      <Footer />
    </div>
);
export default App;

和我这样的路线

const Switches = props => (
  <Switch>
    <Route exact path="/" component={Home} />
    <Route exact path="/projects" component={Home} />
    <Route path="/projects/:ProjectId" component={SingleProject} />
    <Route component={NotFound} contextData={{ is404: true }} />
  </Switch>
);

我想要做的是从我的服务器渲染react应用程序。我在webstorm中遇到一个错误,即renderToString是一个未解析的函数或方法。

我不明白我在这里失踪了什么。 我使用this Github参考。

1 个答案:

答案 0 :(得分:0)

对于您的特定错误,您还必须为您的服务器应用启用JSX。

unexpected token错误是因为解析器无法识别<字符,因为它是JSX的一部分,而不是JavaScript本身。