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

3
我正在尝试使用express.js设置redux服务器端渲染。 我已经完成了设置,但当express在浏览器上呈现页面时,我看到以下错误:
bundle.js文件中的Uncaught SyntaxError: Unexpected token <。我发现,在源选项卡中,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个回答

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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接