"意外的令牌< "什么时候做反应redux服务器端渲染

时间:2016-06-19 09:54:51

标签: javascript reactjs redux

我最近尝试使用express + react + redux

构建通用应用

这是我的问题的简要说明:

我已成功将反应组件呈现为 HTML ,并通过 express ' res.send(renderFullPage(html, initialState))将其发送回客户端。 html在浏览器端正确呈现。但是,我一直在浏览器控制台中收到此错误:

Uncaught SyntaxError: Unexpected token < ... bundle.js: 1`enter code here`

当我通过点击 bundle.js:1 进一步解决问题时,我看到了:

<!doctype html> (x)

我通过在 package.json 中运行npm run devServer命令来启动节点服务器:

```

{
  "name": "universal",
  "version": "1.0.0",
  "author": "Bryan Huang",
  "description": "nodejs isomorphic package",
  "main": "index.js",
  "scripts": {
    "test": "mocha --compilers js:babel-core/register --recursive",
    "devServer": "nodemon server/bin/server.js",
    "buildServer": "babel server/server.js -d build",
    "startServer": "node build/server/server.js",
    "lint": "eslint . --ext .js --ext .jsx",
    "build": "webpack",
    "dev": "webpack-dev-server"
  }
  ...
}

```

服务器/ bin中/ server.js

```

const fs =  require('fs')
const path = require('path')
const config =  JSON.parse(fs.readFileSync(path.resolve(__dirname, '../..', '.babelrc'), 'utf-8'))
require('babel-register')(config)
require(path.resolve(__dirname, '../server.js'))

```

服务器/ server.js

```

import 'babel-polyfill'
import path from 'path'
import React from 'react'
import { renderToString } from 'react-dom/server'
import renderFullPage from './utils/render'
import { createStore } from 'redux'
import { Provider }  from 'react-redux'
import App from '../src/containers/App'
import reducers from '../src/reducers'
import express from 'express'

const app = express()

const staticPath = path.resolve(__dirname, '../..', 'static')

// serve static files.
app.use('/static', express.static(staticPath))

// Fired everytime the server side receives a request.
app.use(handleRender)
app.use(renderFullPage)

function handleRender (req, res) {
  // Create store.
  const store = createStore(reducers)

  // Render the component to string.
  const html = renderToString (
    <Provider store={store}>
      <App />
    </Provider>
  )

  // Get the initial state.
  const initialState = store.getState()

  // Send the rendered page back to client
  res.send(renderFullPage(html, initialState))
}


app.listen(3004, () => {
  console.log('listening in port 3004')
})

```

这是我的renderFullPage功能:

```

export default function renderFullPage (html, initialState) {
  return `<!doctype html>
    <html>
      <head>
        <title>Universal App</title>
      </head>
      <body>
        <div id='app'>${html}</div>
        <script>
          window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}
        </script>
        <script src='build/bundle.js'></script>
      </body>
    </html>
  `
}

```

我做错了导致这个问题吗?

1 个答案:

答案 0 :(得分:0)