我的快递服务器无法识别中间件功能

时间:2017-10-14 20:44:27

标签: javascript node.js reactjs express

我正在做反应中的服务器端渲染,我在express中编写了简单的服务器。不幸的是我一直得到“TypeError('app.use()需要一个中间件函数')”错误。以下是我的app.js的样子:

var express = require('express');
var path = require('path');
var logger = require('morgan');
var httpProxy = require('http-proxy');
var requestHandler = require('./public/requestHandler.bundle.js');
var app = express();

const apiProxy = httpProxy.createProxyServer({
  target:'http://localhost:3001'
});

app.use('/api', function(req,res){
  apiProxy.web(req,res);
})

app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));

app.set('view engine', 'ejs');
app.use(requestHandler); //<------------------


app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});


app.use(function(err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

这是我的requestHandler:

import React from 'react';
import {renderToString} from 'react-dom/server';
import {StaticRouter} from 'react-router-dom';
import {Provider} from 'react-redux';
import {createStore, applyMiddleware} from 'redux';
import thunkMiddleware from 'redux-thunk';
import reducers from '../client/reducers';
import routes from '../client/components/routes';
import axios from 'axios';

function requestHandler(req, res, next) {
  axios.get('http://localhost:3001/books').then(function(response) {
    const createStoreWithMiddleware = applyMiddleware(thunkMiddleware)(createStore);
    const store = createStoreWithMiddleware(reducers, {
      "books": {
        "books": response.data
      }
    })
    const initialState = JSON.stringify(store.getState()).replace(/<\/script/g, '<\\/script').replace(/<!--/g, '<\\\!--');
    const context = {};

    const reactComponent = renderToString(
      <Provider store={store}>
        <StaticRouter location={req.url} context={context}>
          {routes}
        </StaticRouter>
      </Provider>
    );

    if (context.url) {
      redirect(context.status, context.url)
    } else {
      res.status(200).render('index', {reactComponent, initialState})
    }

  })
  .catch(function(err){
        console.log('#Initial Server-side rendering error', err);
      })
};

export default requestHandler;

然后我使用webpack和babel将其编译为es5。为什么我的应用程序不将此功能视为中间件?

我尝试使用CommonJs导出它 - 没有效果

1 个答案:

答案 0 :(得分:1)

您的捆绑包正在导出ES6模块,但您要使用CommonJs导入它。尝试:

app.use(requestHandler.default);