bundle.js显示HTML代码而不是javascript

时间:2017-09-29 07:02:40

标签: javascript node.js reactjs webpack redux

我正在尝试使用express.js设置redux服务器端渲染。我几乎完成了设置hpwever,我在浏览器上快速呈现页面时看到以下错误

Uncaught SyntaxError: Unexpected token <文件中的

bundle.js。我发现在源选项卡中,bundle.js正在使用HTML代码而不是我的webpack构建的编译js代码。我认为这是导致错误的问题。

以下是有助于找出我出错的地方的文件

Project structure

服务器 index.js

'use strict';

import express from 'express';
import webpack from 'webpack';
import path from 'path';
import config from '../webpack.config.js';
import open from 'open';
import chalk from 'chalk';
import bodyParser from 'body-parser';
import handleRender from '../client/src/utils/handleRender.js';

const port = 3000;
const app = express();

webpack(config).run((err, results) => {
  console.log(err);
  console.log(results);
});

app.use(bodyParser.json());
app.use(handleRender);

// Trigger server
app.listen(port, function(err) {
  if (err) {
    console.log(chalk.red("Whoa!!! Server crashed..."), err);
  } else {
    console.log(chalk.green("YAY!!! Server is up and running..."));
    // open(`http://localhost:${port}/home`);
  }
});

renderFullPage.js

'use strict';

function renderFullPage(html, preloadedState) {
  return `
    <!doctype html>
    <html>
      <head>
        <title>Redux Universal Example</title>
      </head>
      <body>
        <div id="root">${html}</div>
        <script>
          // WARNING: See the following for security issues around embedding JSON in HTML:
          // http://redux.js.org/docs/recipes/ServerRendering.html#security-considerations
          window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, '\\u003c')}
        </script>
        <script type=text/javascript src="../../../build/bundle.js"></script>
      </body>
    </html>
    `
}

export default renderFullPage;

handleRender.js

'use strict';

import React from 'react';
import { renderToString } from 'react-dom/server';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import renderFullPage from './renderFullPage.js';
import App from '../containers/App.js';
import rootReducer from '../reducers';

const handleRender = (req, res) => {
  // Create a new Redux store instance
  const store = createStore(rootReducer);

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

  // Grab the initial state from our Redux store
  const preloadedState = store.getState();

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

export default handleRender;

如果需要任何其他信息,请告诉我。在此先感谢!!!

1 个答案:

答案 0 :(得分:1)

您未将捆绑文件暴露给浏览器。您的脚本src ../../../build/bundle.js无法正常工作 - 该文件仅在您的本地计算机上,而不是在服务器上。

在服务器index.js文件中,您需要将构建目录设置为express的静态资源:

app.use(express.static(path.join(__dirname, './build'), { maxAge: 30 * 60 * 60 * 24 * 1000 }));

然后更新您的脚本src:<script type=text/javascript src="/bundle.js"></script>